WMI/WQL 查询 powershell 中的双反斜杠

double backslash in WMI/WQL query powershell

我的 WQL 查询遇到了奇怪的问题。

$SCCMQuery = @'
Select UAR.User, UAR.Application, UAR.CurrentState from sms_fullcollectionmembership as FCM
INNER JOIN SMS_UserApplicationRequest as UAR ON UAR.User=FCM.SMSID
where FCM.CollectionID="a0104"
'@
$Results = Get-WmiObject -Namespace "root\SMS\Site_Name" -Query $SCCMQuery

以上查询无法正常工作,但是当我像这样在 FCM.CollectionID 中添加另一个反斜杠时 (a\100104) 然后它开始工作。

有人可以告诉我为什么它会这样工作吗?我无法手动将反斜杠放入所有值中,因为它们稍后会从其他 WMI 查询生成。

尽管 \ 在 PowerShell 中只是一个文字字符,但在 WQL 中它仍然是一个 转义字符

来自the specification

WQL uses terminologies and concepts, as specified in [DMTF-DSP0004], except as noted below, and requires familiarity with the CIM model. The server MUST treat a backslash as an escape character in a WQL query, except within a LIKE clause. The server MUST treat literal strings in WQL data as case-insensitive, contrary to what [DMTF-DSP0004] specifies.

Use 可以使用 -replace 运算符来转义反斜杠(请注意 -replace 的第一个参数是一个正则表达式模式,它也将反斜杠视为转义字符):

$escapedWmiQueryValue = $WmiQueryValue -replace '\','\'

如果您查看 about_wql,您会看到

WQL uses the backslash () as its escape character. This is different from Windows PowerShell, which uses the backtick character (`).

在您生成的查询中,您可以根据需要通过简单的替换人为地添加斜线。

$SCCMQuery.replace("\","\")

我确信 $SCCMQuery 只是一个测试示例,但查询必须放在代码中的某个地方。