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

PowerShell远程写入注册表时变量失效问题求助

问题原因与解决办法

原因

Invoke-Command的脚本块是在远程计算机的独立PowerShell会话中执行的,你本地定义的$version变量默认不会被自动传递到远程会话。远程执行时脚本块里的$version实际是未定义的空值,所以写入注册表的内容为空。

解决方法

有两种常用方式可以将本地变量传递到远程会话:

方法1:使用-ArgumentList传递参数

通过-ArgumentList把本地变量传给远程脚本块,脚本块内可以用$args数组接收,或者定义参数变量提升可读性:

# 用$args接收参数
Invoke-Command -ComputerName $PC[0] -ArgumentList $version {
    Set-ItemProperty -Path "HKLM:\SOFTWARE\XXX\YYY" -Name "Version" -Value $args[0]
}

# 定义参数变量接收(更清晰)
Invoke-Command -ComputerName $PC[0] -ArgumentList $version {
    param($targetVersion)
    Set-ItemProperty -Path "HKLM:\SOFTWARE\XXX\YYY" -Name "Version" -Value $targetVersion
}

方法2:使用$using:作用域修饰符(PowerShell 3.0及以上支持)

直接在远程脚本块里用$using:前缀引用本地变量,PowerShell会自动把本地变量的值传递到远程会话:

Invoke-Command -ComputerName $PC[0] {
    Set-ItemProperty -Path "HKLM:\SOFTWARE\XXX\YYY" -Name "Version" -Value $using:version
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:55:39