Skip to content

Instantly share code, notes, and snippets.

@DBremen
Created November 13, 2015 14:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save DBremen/0b168d96e0a5b362f4f7 to your computer and use it in GitHub Desktop.
Save DBremen/0b168d96e0a5b362f4f7 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
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