Search all Server Shares for a wildcard filename

1.2k Views Asked by At

I'm looking for a PowerShell script that will search all shares on a server for a wildcard of *_HELP_instructions*. An example of a files that it would search for would be 12_HELP_INSTRUCTIONS.txt or 22_HELP_INSTRUCTIONS.html.

So far I have the script below that will search the contents of the C:\, but I need a script that I can setup to search server shares instead.

$FilesToSearch = Get-ChildItem "C:\*" -Recurse -ErrorAction SilentlyContinue |
                 where {$_.Name -like "*_HELP_instructions*"}

if ($FilesToSearch -ne $null) {
    Write-Host "System Infected!" 
    exit 2015
} else {
    Write-Host "System Not Infected!" 
    exit 0
}
3

There are 3 best solutions below

1
Ansgar Wiechers On BEST ANSWER

Use Get-WmiObject to enumerate the shared folders on the server:

$exclude = 'Remote Admin', 'Remote IPC', 'Default share'
$shared  = Get-WmiObject Win32_Share |
           Where-Object { $exclude -notcontains $_.Description } |
           Select-Object -Expand Path

The Where-Object clause excludes the administrative shares from being scanned (otherwise you could simply scan all local drives).

Then call Get-ChildItem with the resulting list of paths:

$FilesToSearch = Get-ChildItem $shared -Filter '*_HELP_instructions*' -Recurse -ErrorAction SilentlyContinue
5
Lachie White On

You could use a ForEach Loop to loop through all the paths you are required to search through.

$paths = Get-Content C:\Temp\Pathlist.txt

Foreach($path in $paths){
   $Filestosearch = Get-ChildItem $path -Recurse -ErrorAction SiltenlyContinue| where {$_.Name -like "*_HELP_instructions*"}
   If($FilesToSearch -ne $null) {
      Write-Host "System Infected!" 
   $Filestosearch | Export-Csv c:\Temp\Result.csv -NoTypeInformation -Append
   } else {
      Write-Host "System Not Infected!" 
      }
}

This will loop through each $path in the C:\Temp\PathList.txt file. (e.g. C:\* or \\ServerName\MyShare\*)

Then push the output to C:\Temp\Result.csv. If the System is Infected.

This will take a while to run depending on how many paths you put in the txt file. But it will achieve what you are after!

Hope this helps!

0
Mark Smith On

Thanks very much guys for your feedback. Taking all of your coments into account the final code was as follows:

$exclude = 'Remote Admin', 'Remote IPC', 'Default share'
$shared  = Get-WmiObject Win32_Share |
       Where-Object { $exclude -notcontains $_.Description } |
       Select-Object -Expand Path

$FilesToSearch = Get-ChildItem $shared -Filter '*_HELP_instructions*' -Recurse -ErrorAction SilentlyContinue

If($FilesToSearch -ne $null) 

{
Write-Host "System Infected!" 
exit 2015
}

else 

{
Write-Host "System Clear!" 
exit 0
}