我有一根绳子。有时它看起来像这样:
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)
Run Code Online (Sandbox Code Playgroud)
这不起作用,所以我尝试将字符串用双引号而不是单引号括起来。
$string = "9xABp'}H9$G(@"
$secure = ConvertTo-SecureString -String $string -AsPlainText -Force
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
Run Code Online (Sandbox Code Playgroud)
没关系,但是不包括 $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)
Run Code Online (Sandbox Code Playgroud)
但$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)
Run Code Online (Sandbox Code Playgroud)
我在这里能做什么?
PowerShell 此处字符串的存在就是为了应对这种情况。
$string = @"
'9xABp'}H9$G(@'
"@
Run Code Online (Sandbox Code Playgroud)
和字符必须独占一行,但允许其中包含任何字符@"。"@
感谢 Mike Klement 提醒我注意单引号变体,如果您的密码可能包含$在 PowerShell 中有意义的一个或另一个字符,则应该使用单引号变体。
$string = @'
'9xABp'}H9$G(@'
'@
Run Code Online (Sandbox Code Playgroud)
这与前面的here-string 的工作方式相同,但是这个不会扩展变量,并且更适合。
| 归档时间: |
|
| 查看次数: |
3752 次 |
| 最近记录: |