在 Powershell 中转义与号 (&) 和加号 (+)

Escaping ampersand (&) and plus sign (+) in Powershell

我正在尝试对 Active Directory 执行 Set-ADUser 命令,以便将 mobiletitle 属性更新为下面:

Set-ADUser -Identity "UID1234" -Mobile "+2345678" -Server $domainController[0] -Credential $mycred;

这条命令通过。不幸的是,帐户中的加号 (+) 已被替换为 space。

我也想执行相同的命令来更新 title 属性:

Set-ADUser -Identity "UID1234" -Title "Employee & Manager" -Server $domainController[0] -Credential $mycred;

在这里,我收到以下错误: The string is missing the terminator \" 因为与号 (&) 字符不被理解为正确的字符,因为它通常用于调用变量。

对于这两种情况,我知道应该有一种方法来转义这些字符,但我使用反斜杠 () 或反单引号 (`) 等转义符没有成功。

任何帮助将不胜感激!

我有两个建议。首先,尝试在文本周围使用单引号而不是双引号。 PowerShell 会将单引号之间的任何文本视为文字。

示例:

$i = 10
Write-Host 'The value of i is $i'
> The value of i is $i

其次,

如果您希望保留双引号(您必须这样做才能使其生效),请在“&”和“+”符号前放置一个`(Backtick/grave 重音字符)。

"`+2345678"
"Employee `& Manager"

要转​​义 & 符号,您可以尝试用双引号将其括起来,例如'Employee "&" Manager'
参考 https://github.com/arcanecode/PowerShell/issues/1