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)
我可以在这里做什么?
解决方案
PowerShell herestring 就是为这样的场合而存在的。
$string = @"
'9xABp'}H9$G(@'
"@
和字符必须在自己的行中,但允许其中的任何字符@"
。"@
编辑
$
感谢 Mike Klement 提醒我单引号变体,如果您的密码可能包含在 PowerShell 中具有重要意义的一个或另一个字符,则应使用该变体。
$string = @'
'9xABp'}H9$G(@'
'@
这与前一个 here-string 的工作方式相同,但这个不会扩展变量,并且更适合。
推荐阅读
- python - 哪种方式是在 python 中获取部分字符串的最佳方式?
- apache-spark - 将数据帧缓存在分区或更多分区中是否更有效
- c# - 在 WebBrowser 文档中获取鼠标点击坐标
- javascript - 替换正则表达式javascript
- python - 如何在字符串中交替更改大写和小写?
- sql-server - 无法使用 SQLCMD.EXE,因为它不存在
- java - IsReadyToPayRequest.fromJson,无法解析方法“fromJson java.lang.string”
- bash - 捕获分离命令的输出使执行顺序
- computer-vision - 如何校准 realsense D435 相机以使用 ORBSLAM2
- shell - 通过 Grep 命令从文件中搜索仅包含特定符号和数字的字符串