我没有成功让以下代码片段输出“Hello World!” 在 PS7
$string = $("Hello World!" | ConvertTo-SecureString -AsPlainText -Force)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($string))
Run Code Online (Sandbox Code Playgroud)
上面的代码是一个不指定长度解密安全字符串的例子。
相同的代码适用于 PS6 和 PS5 以完全解密安全字符串,但不适用于 PS7。我发现解决这个问题的唯一方法是使用 PtrToStringBSTR。然后它可以在此用例的所有 PS 版本中按预期工作。
我在 Github 上的 Powershell 存储库中提出了一个问题,但没有任何回应。老实说,我只是想确认其他人的行为是否相同。
https://github.com/PowerShell/PowerShell/issues/11953
我认为对于许多移植到 PS7 的代码来说,这样的事情将是一个突破性的变化。
这是我迄今为止发现的:
文档
根据文档,指定整数时,PtrToStringAuto:
Allocates a managed String and copies the specified number of characters from a string stored in unmanaged memory into it.
指定 11 的 int 返回“Hello”,这是因为返回的所有其他字符都是 Null。在这种情况下,您必须指定一个 23 的 int 以返回完整的字符串“Hello World!” 使用这种方法。我已经将输出存储在一个变量中来演示这一点。
$String = $("Hello World!" | ConvertTo-SecureString -AsPlainText -Force)
[System.Runtime.InteropServices.Marshal]::PtrToStringAuto(
[System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($string), 23) …Run Code Online (Sandbox Code Playgroud)