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

PS 7.4.6执行BitLocker解锁脚本报错,PS 5.1正常,求原因?

在PowerShell 7.4中运行BitLocker解锁脚本报错,但PowerShell 5.1中正常的原因及解决方法

问题重现

脚本代码:

$DriveLetter = Read-Host "Drive letter"
$DriveLetter = ($DriveLetter + ":")
$EncUserCredential = Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString
gsudo pwsh.exe -CommandWithArgs '`$parm1 = ConvertTo-SecureString -String `$args[1]; Unlock-Bitlocker -MountPoint `$args[0] -Password `$parm1' $DriveLetter $EncUserCredential

在PowerShell 7.4.6中直接运行时出现错误:

Drive letter: w
Enter Password: ********************
Unlock-BitLocker: Cannot process argument transformation on parameter 'Password'. Cannot convert the value of type "System.String" to type "System.Security.SecureString".

但在PowerShell 5.1中运行该脚本(调用PowerShell 7.4)时正常工作。

原因分析

核心问题是PowerShell 7+与PowerShell 5.1的命令行参数序列化逻辑差异:

  • 当在PowerShell 7.4中直接调用gsudo pwsh.exe -CommandWithArgs时,加密后的SecureString字符串($EncUserCredential)在传递到目标PowerShell 7进程时,会被解析器错误地添加额外转义字符或引号,导致ConvertTo-SecureString无法正确将其还原为SecureString类型,最终传递给Unlock-BitLocker的是一个无效的普通字符串,触发类型转换错误。
  • 而在PowerShell 5.1中调用时,参数传递的序列化逻辑兼容目标PowerShell 7进程,加密字符串能被正确解析并转换为SecureString,因此脚本正常执行。

另外关于脚本执行策略:PowerShell 7的执行策略是独立于PowerShell 5.1的,仅给5.1设置允许未签名脚本不会影响7的策略,需要单独配置7的执行策略。

解决方案

使用-EncodedCommand传递Base64编码后的命令,避免参数转义问题:

$DriveLetter = Read-Host "Drive letter"
$DriveLetter = ($DriveLetter + ":")
$EncUserCredential = Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString

# 构建完整命令并替换变量
$commandContent = @"
`$securePassword = ConvertTo-SecureString -String '$EncUserCredential'
Unlock-Bitlocker -MountPoint '$DriveLetter' -Password `$securePassword
"@

# 将命令编码为Base64(PowerShell要求Unicode编码)
$encodedCommand = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($commandContent))

# 通过gsudo调用PowerShell 7并执行编码后的命令
gsudo pwsh.exe -EncodedCommand $encodedCommand

执行策略配置

若需要在PowerShell 7中运行未签名脚本,可在PowerShell 7终端中执行:

Set-ExecutionPolicy RemoteSigned -Scope CurrentUser

(根据实际需求调整策略和作用域,比如Unrestricted或LocalMachine)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 07:20:16