首页 > 解决方案 > 处理密码字符串中的特殊字符

问题描述

我有一个字符串。有时它看起来像这样:

9xABp'}H9$G(@

虽然,有时它看起来像这样:

9xABp"}H9$G(@

我无法控制用于生成字符串的字符集,但我需要让 Powershell 停止抱怨无法解析字符串并给我所有字符。

$string = '9xABp'}H9$G(@'
$secure = ConvertTo-SecureString -String $string -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

这不起作用,所以我尝试用双引号而不是单引号将我的字符串括起来。

$string = "9xABp'}H9$G(@"
$secure = ConvertTo-SecureString -String $string -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

很好,但是不包括 $G (由反斜杠代替),当我的字符串里面有双引号时怎么办?

我尝试使用 [Regex]::Escape()。

$string = "9xABp'}H9$G(@"
$secure = ConvertTo-SecureString -String ([Regex]::Escape($string)) -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

但是 $G 仍然丢失。再试一次,这次在外面加上双引号和单引号。

$string = "'9xABp'}H9$G(@'"
$secure = ConvertTo-SecureString -String ([Regex]::Escape($string)) -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

我可以在这里做什么?

标签: powershell

解决方案


PowerShell herestring 就是为这样的场合而存在的。

$string = @"
'9xABp'}H9$G(@'
"@

和字符必须在自己的行中,但允许其中的任何字符@""@

编辑

$感谢 Mike Klement 提醒我单引号变体,如果您的密码可能包含在 PowerShell 中具有重要意义的一个或另一个字符,则应使用该变体。

$string = @'
'9xABp'}H9$G(@'
'@

这与前一个 here-string 的工作方式相同,但这个不会扩展变量,并且更适合。


推荐阅读