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


is there "best practice" way of escaping characters in wmi query (or preferred alternative, such sort of wmi equivalent dbparameter)?

currently i've rolled own, sort of thing there safer options; though far i've not found any.

my roll-your-own implementation

use regex replace ensure backslash, apostrophe , quote characters prefixed 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 * win32_service name = "{0}"'     }     process {         get-wmiobject -query (convertto-wmiescapedquery -query $query -parameters $servicename)     } } get-wmiservice 'john''s example service' 


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -