处理密码字符串中的特殊字符

时间:2020-05-04 20:37:01

标签: powershell

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

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)

我在这里可以做什么?

1 个答案:

答案 0 :(得分:2)

PowerShell此处字符串仅在这种情况下存在。

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

@""@字符必须位于自己的行上,但允许其中包含任何字符。

编辑

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

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

此功能与上一个here-string相同,但是此字符串不会扩展变量,更合适。