powershell 通过'PowerShellFilter'参数支持PowerShell查询语法的Get-WmiObject和Get-CimInstance的代理命令
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 通过'PowerShellFilter'参数支持PowerShell查询语法的Get-WmiObject和Get-CimInstance的代理命令相关的知识,希望对你有一定的参考价值。
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))
}
以上是关于powershell 通过'PowerShellFilter'参数支持PowerShell查询语法的Get-WmiObject和Get-CimInstance的代理命令的主要内容,如果未能解决你的问题,请参考以下文章
PowerShell启用多跳远程控制
PowerShell启用多跳远程控制
你如何使用 PowerShell? [关闭]
是否可以/如何使用某些 cmdlet 停止 powershell?
为啥不能使用 VariablesToExport 导出 PowerShell 模块中的变量成员?
无法在 Visual Studio Code 中调试 PowerShell 脚本