停止单引号转义 WMI 查询 powershell 中的字符串
Stop a single quote from escaping a string in a WMI query powershell
我有一些使用 WMI 查询的代码,但我 运行 遇到一个问题,我使用的变量有一个 '(单引号),这会导致代码出现故障
这是一个例子:
$path = "\SERVER1\Mike O'Leary$"
$servername = $path.Split('\')[2].Split('\')[0]
$sharename = $path -replace ".*\" -replace "'", "`'"
Get-WmiObject Win32_share -computer $servername -filter "name='$sharename'" | Select Name,Path
问题是共享名称包含一个 ' 字符,所以它出错了。没有 ' 的路径工作正常
我尝试使用上面看到的替换,但这没有帮助
我尝试了各种引号组合,但我无法正确组合,有人可以帮忙吗?
谢谢
本
糟糕,原来我应该使用 \ 而不是 `
$path = "\SERVER1\Mike O'Leary$"
$servername = $path.Split('\')[2].Split('\')[0]
$sharename = $path -replace ".*\" -replace "'", "\'"
Get-WmiObject Win32_share -computer $servername -filter "name='$sharename'" | Select Name,Path
谜底已解!
您需要在 WQL 中转义该字符。涉及此内容的 blog 表示您可以使用反斜杠将其转义。
$sharename = $path -replace ".*\" -replace "'", "\'"
在过滤字符串中使用双引号而不是单引号:
Get-WmiObject Win32_Share -Computer $servername -Filter "name=`"$sharename`"" | ...
嵌套的双引号必须在前面加上反引号,以便在双引号过滤字符串中对它们进行转义。
我有一些使用 WMI 查询的代码,但我 运行 遇到一个问题,我使用的变量有一个 '(单引号),这会导致代码出现故障
这是一个例子:
$path = "\SERVER1\Mike O'Leary$"
$servername = $path.Split('\')[2].Split('\')[0]
$sharename = $path -replace ".*\" -replace "'", "`'"
Get-WmiObject Win32_share -computer $servername -filter "name='$sharename'" | Select Name,Path
问题是共享名称包含一个 ' 字符,所以它出错了。没有 ' 的路径工作正常
我尝试使用上面看到的替换,但这没有帮助
我尝试了各种引号组合,但我无法正确组合,有人可以帮忙吗?
谢谢 本
糟糕,原来我应该使用 \ 而不是 `
$path = "\SERVER1\Mike O'Leary$"
$servername = $path.Split('\')[2].Split('\')[0]
$sharename = $path -replace ".*\" -replace "'", "\'"
Get-WmiObject Win32_share -computer $servername -filter "name='$sharename'" | Select Name,Path
谜底已解!
您需要在 WQL 中转义该字符。涉及此内容的 blog 表示您可以使用反斜杠将其转义。
$sharename = $path -replace ".*\" -replace "'", "\'"
在过滤字符串中使用双引号而不是单引号:
Get-WmiObject Win32_Share -Computer $servername -Filter "name=`"$sharename`"" | ...
嵌套的双引号必须在前面加上反引号,以便在双引号过滤字符串中对它们进行转义。