PowerShell:向 Get-WmiObject 添加过滤器或查询

PowerShell: Adding filter or query to Get-WmiObject

我正在尝试向一行 PowerShell 代码添加过滤器或查询,但我得到了奇怪的结果。我可以使用任何 WMI 查询来复制这个问题。这是一个例子:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command "Get-WmiObject -class Win32_Processor -Namespace root\cimv2 -filter 'Status = `"OK`"'"

这给了我这个错误:Get-WmiObject:无效查询 "select * from Win32_Processor where Status = OK"。但是如果我 运行 它在已经打开的 PowerShell window 中,像这样:

Get-WmiObject -class Win32_Processor -Namespace root\cimv2 -filter 'Status = "OK"'

效果很好。所以我不理解这种行为。我尝试了各种单引号、双引号和转义字符,但似乎没有任何效果。

您的问题是对使用 cmd 解析器进行引用的误解(调用 powershell.exe 时使用的):

powershell.exe -Command ""

双引号之间的所有内容都将传递给 -Command。在您的情况下,最简单的方法是转义单引号(通过加倍计数),因为 cmd 以特殊方式处理双引号(通常通过删除它们):

powershell.exe -Command "Get-WmiObject -Class Win32_Processor -Filter 'Status = ''OK'''"

作为脚注,root/cimv2Get-WmiObject

的默认命名空间