Monthly Archive

Categories

File searches with WMI

I saw a question about file searches with WMI.

If you just know the file name it’s a very slow process. Painfully slow.

If you have an idea about the folder its much quicker.

 

function get-wmifile {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]$path,

[string]$file

)

if ($path.IndexOf('\\') -le 0 ){
$path = $path.replace('\', '\\')
}

if ($path.IndexOf('*') -ge 0 ){
$path = $path.replace('*', '%')
}

Write-Verbose -Message "Path to search: $path"

$folders = Get-CimInstance -ClassName Win32_Directory -Filter "Name LIKE '$path'" 
foreach ($folder in $folders){

if ($file) {
Get-CimAssociatedInstance -InputObject $folder -ResultClassName CIM_DataFile |
where Name -Like "*$file" |
Select Name
}
else {
Get-CimAssociatedInstance -InputObject $folder -ResultClassName CIM_DataFile |
Select Name
}
}

}

 

Take the path and replace any single \ with \\. WMI expects c:\\test NOT c:\test.

Likewise replace the wildcard * with the WMI wildcard equivalent %

Get the folders that are like the path. Foreach folder use the WMI association between Win32_Directory and CIM_datafile to get the files. if you’ve specified a file then just return that otherwise all files in the folders matching path.

 

The WMI approach works and if you add in the computer name you can use remoting to get the answer from a remote machine.

 

As a comparison using Get-ChildItem would be

PS> Get-ChildItem -Path c:\test* -Recurse -Filter 'p1.txt' | select Fullname

which is much quicker.

 

Using WMI to do this is a fun exercise but the fastest approach is to use Get-ChildItem

Comments are closed.