What's the correct way to escape a WMI string?

649 Views Asked by At

Is there a "best practice" way of escaping characters in a WMI query (or a preferred alternative, such as some sort of WMI equivalent to DbParameter)?

Currently I've rolled my own, but generally for this sort of thing there are safer options; though so far I've not found any.

My Roll-Your-Own Implementation

Use a regex replace to ensure backslash, apostrophe and quote characters are prefixed with backslashes:

function ConvertTo-WmiEscapedQuery {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Query
        ,
        [Parameter()]
        [string[]]$Parameters = @()
    )
    begin {
        [string]$EscapeCharatersRegex = '([\\''"])'
    }
    process {
        [string[]]$EscapedParameters = $Parameters | %{$_ -replace $EscapeCharatersRegex, '\$1'}
        $Query -f $EscapedParameters
    }
}

Example Usage Scenario

function Get-WmiService {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$ServiceName
    )
    begin {
        [string]$Query = 'select * from win32_service where name = "{0}"'
    }
    process {
        Get-WmiObject -Query (ConvertTo-WmiEscapedQuery -Query $Query -Parameters $ServiceName)
    }
}
Get-WmiService 'John''s Example Service'
0

There are 0 best solutions below