Accessing individual Files and Folders Remotely via WMI

by Apr 7, 2009

WMI is an excellent way of remotely checking files or folders since it has the ability to access individual files and folders, and also works locally as well as remotely. Files are represented by the WMI class CIM_DataFile whereas folders are represented by Win32_Directory.

However, you should never ask WMI for all instances of either class. Doing so would enumerate every single file or folder on any drive on the target computer, which not only takes a long time but also can easily let you run out of memory and lock down the CPU.

Always use specific filters when accessing files or folders. The next line gets you all folders in the root folder of drive C:. To use this remotely, add the -computername property to Get-WMIObject:

Get-WmiObject Win32_Directory -filter 'Drive="C:" and Path="\"' | Format-Table name

The next line retrieves all log files in your Windows folder, assuming the Windows folder is C:windows on the target system:

Get-WmiObject CIM_DataFile -filter `
'Drive="C:" and Path="\Windows\" and Extension="log"' | Format-Table Name

Note that both examples limit information to only the Name property. You can get back any kind of information, such as file size and write times:

Get-WmiObject CIM_DataFile -filter `
'Drive="C:" and Path="\Windows\" and Extension="log"' | Format-List *

Avoid using the like operator. The next line would get you all log files in the Windows folder and recursively in all sub-folders. However, WMI would now query every single file which takes a very long time:

#Get-WmiObject CIM_DataFile -filter `
# 'Drive="C:" and Path like "\Windows\%" and Extension="log"' | Format-Table Name