You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PowerShell含临时变量的代码改写为单行命令?

PowerShell临时变量消除方案

一、解密代码消除临时变量

你原来的解密代码用到了$Secr和$BSTR两个仅用一次的临时变量,完全可以合并成单行命令。之前的写法无效,是因为方法的参数中不能直接使用管道表达式,必须用子表达式$()把管道执行的结果先计算出来。

完全消除临时变量的单行写法

$Decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($($Encrypted | ConvertTo-SecureString -Key $Key)))

分步消除的写法(先移除$Secr)

如果觉得单行太长,也可以先只去掉$Secr,写法如下:

$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($($Encrypted | ConvertTo-SecureString -Key $Key))
$Decrypted = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

二、加密代码消除$GetKey变量

要消除$GetKey变量,直接把Get-Content命令用$()包裹,作为-key参数的值即可——PowerShell会优先执行子表达式里的命令,再把结果传给参数。

优化后的代码

$Text = "Test Message"
$Encrypted = ConvertTo-SecureString $Text -AsPlainText -Force | ConvertFrom-SecureString -key $(Get-Content "C:\temp\AESKey.AES.Key")

如果$Text也不需要复用,还可以进一步简化:

$Encrypted = ConvertTo-SecureString "Test Message" -AsPlainText -Force | ConvertFrom-SecureString -key $(Get-Content "C:\temp\AESKey.AES.Key")

内容的提问来源于stack exchange,提问作者Ωmega

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 07:54:53