Search code examples
powershellwmi

PowerShell WMI filter on variable


This is not the exact scenario of what I'm trying to accomplish but is a good example of where I am stuck.

$Path = "\\192.168.1.1\config"
Get-CimInstance -Namespace ROOT\CIMV2 -ClassName Win32_MappedLogicalDisk -Filter "ProviderName=$Path"

This produces an "Invalid Query" error as it's trying to use \\ in the query

I know I can do this manually by using:

Get-CimInstance -Namespace ROOT\CIMV2 -ClassName Win32_MappedLogicalDisk -Filter "ProviderName='`\\`\\192.168.1.1`\\config'"

This doesn't solve my problem as I need to pass the value from a variable

Any help would be greatly appreciated


Solution

  • You can do an inline replace to escape the backslashes:

    $Path = "\\192.168.1.1\config"
    Get-CimInstance -Namespace ROOT\CIMV2 -ClassName Win32_MappedLogicalDisk -Filter "ProviderName='$($Path -replace '\\','\\')'"
    

    Note: Don't forget to put single quotes around the value part of the filter.

    $() is the subexpression operator. Since -replace uses regex, a single \ must also be escaped for the match expression.