-
-
Save KurtDeGreeff/537ce9ff8c36e4a8d232 to your computer and use it in GitHub Desktop.
Proxy commands for Get-WmiObject and Get-CimInstance that support PowerShell query syntax via 'PowerShellFilter' paramater
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment