PowerShell for Windows Admins

Aug 19 2018   8:12AM GMT

File searches with WMI

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


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 {
param (
[Parameter(Mandatory = $true)]



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

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: