Skip to content

Instantly share code, notes, and snippets.

@DBremen
Last active March 16, 2017 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DBremen/c4f207a38eae079e9469 to your computer and use it in GitHub Desktop.
Save DBremen/c4f207a38eae079e9469 to your computer and use it in GitHub Desktop.
Query WMI with PowerShell syntax
function Get-WmiPowerShell {
[CmdletBinding()]
Param
(
[Parameter(Mandatory)]$Class,
[Parameter(Mandatory)]$Filter
)
$errors = $tokens = $null
$AST= [Management.Automation.Language.Parser]::ParseInput($filter.ToString().Replace('$null','NULL'), [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 }
}
}
$PSBoundParameters.Filter = $wql -join ' '
Get-WmiObject @PSBoundParameters
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment