1

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'
sodawillow
  • 12,497
  • 4
  • 34
  • 44
JohnLBevan
  • 22,735
  • 13
  • 96
  • 178
  • NB: Posted the same question on CodeReview as this falls into the grey area between the sites: http://codereview.stackexchange.com/questions/160021/escaping-characters-in-a-wmi-query – JohnLBevan Apr 06 '17 at 14:23
  • 2
    I think what you are doing here, is what we all have to do. I am not aware of another way but certainly going to follow this thread! – Richard Dakin Apr 06 '17 at 14:39
  • 2
    I keep going back to the CR question and I have nothing to add. I have not found any compelling documentation to suggest what you are doing is incorrect or missing anything. – Matt Apr 06 '17 at 15:51
  • NB: Per comments on CodeReview, the above code does not work. Escaping of quotes should only be done when within quotes of the same type; otherwise we get an error. See code review (link in first comment, above) for more. – JohnLBevan Apr 07 '17 at 09:19

0 Answers0