DBremen
11/13/2015 - 2:25 PM

Proxy commands for Get-WmiObject and Get-CimInstance that support PowerShell query syntax via 'PowerShellFilter' paramater

Proxy commands for Get-WmiObject and Get-CimInstance that support PowerShell query syntax via 'PowerShellFilter' paramater

foreach ($command in ('Get-WmiObject','Get-CimInstance')){
    $Metadata = New-Object System.Management.Automation.CommandMetaData (Get-Command $command)
    $proxyCmd = [System.Management.Automation.ProxyCommand]::Create($Metadata) #| clip
    if ($command -eq 'Get-WmiObject'){
    $newParam = @'
[Parameter(ParameterSetName='query')]
[ScriptBlock]
$PowerShellFilter,
'@
    }
    else{
    $newParam = @'
    [Parameter(ParameterSetName='ResourceUriComputerSet')]
    [Parameter(ParameterSetName='ResourceUriSessionSet')]
    [Parameter(ParameterSetName='ClassNameComputerSet')]
    [Parameter(ParameterSetName='ClassNameSessionSet')]
    [ScriptBlock]
    $PowerShellFilter,
'@
    }
    $proxyCmd = $proxyCmd.Insert($proxyCmd.IndexOf('param(')+7,$newParam)
    $newCode = @'
    if ($PSBoundParameters.ContainsKey('PowerShellFilter')){
        $errors = $tokens = $null
        $AST= [Management.Automation.Language.Parser]::ParseInput($PowerShellFilter, [ref]$tokens, [ref]$errors)
        $tokens = $tokens | where { $_.Text -and $_.Name -ne '_' -and $_.Kind -ne 'Dot' }
        $htReplacements = @"
eq = =
lt = <
gt = >
le = <=
ge = >=
ne = !=
like = like
and = and
or = or
is = is
isnot = is not
"@ | ConvertFrom-StringData
        $wql = foreach ($token in $tokens) {
            switch($token){
                { $_.Value -ne $null }                             { "'$(([Management.Automation.WildcardPattern]$_.Value).ToWql())'"; break }
                { $_.Kind -eq 'Parameter' }                        { $htReplacements."$($_.ParameterName)"; break }
                { [string]$_.TokenFlags -like '*BinaryOperator*' } { $htReplacements."$($_.Text.Replace('-',''))"; break }
                { $_.Kind -eq 'Variable' }                         { "'$(Get-Variable $_.Name -ValueOnly)'"; break }
                Default                                            { $_.Text }
            }
        } 
        $null = $PSBoundParameters.Add('Filter',($wql -join ' '))
        $null = $PSBoundParameters.Remove('PowerShellFilter')
    }
'@
    $proxyCmd = $proxyCmd.Insert($proxyCmd.IndexOf("['OutBuffer'] = 1")+28,$newCode)
    Set-Item -Path function:$command -Value ([ScriptBlock]::Create($proxyCmd))
}