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

如何通过Invoke-Command在远程计算机运行CMD脚本?

解决远程执行Install.cmd的PowerShell变量传递问题

嘿,我立刻就发现你的问题啦——你在本地定义的$remotedir变量,没办法直接在远程会话里使用!PowerShell的远程会话有独立的作用域,本地变量不会自动“同步”到远程那边,所以你的脚本块里调用$remotedir的时候,远程会话根本不知道这个变量指的是什么,自然没法正确执行Install.cmd。

下面给你两种靠谱的解决办法:

方法1:用-ArgumentList传递变量

这是兼容性比较好的方式,适用于所有PowerShell版本:

$remoteinst = "\Windows\Temp\MyFolder"
$remotecomp = "ComputerName" # 记得这里要填实际的远程计算机名
$remotesess = New-PSSession $remotecomp
$remotedir = "C:" + $remoteinst + "\Install.cmd"
# 用param定义脚本块参数,通过-ArgumentList传递本地变量
Invoke-Command -Session $remotesess -ScriptBlock { 
    param($installPath)
    & $installPath # 调用cmd文件
} -ArgumentList $remotedir

方法2:用Using:作用域修饰符(PowerShell 3.0+)

如果你的PowerShell版本是3.0及以上,这个方法更简洁,直接引用本地变量:

$remoteinst = "\Windows\Temp\MyFolder"
$remotecomp = "ComputerName"
$remotesess = New-PSSession $remotecomp
$remotedir = "C:" + $remoteinst + "\Install.cmd"
# Using:前缀告诉远程会话使用本地的$remotedir变量
Invoke-Command -Session $remotesess -ScriptBlock { 
    & $Using:remotedir
}

额外注意事项

  • 先确认远程计算机上的C:\Windows\Temp\MyFolder目录存在,且Install.cmd文件确实在这个路径下
  • 你的账户必须拥有远程计算机的执行权限,并且远程机器已经正确配置了WinRM服务
  • 如果Install.cmd需要管理员权限运行,记得在Invoke-Command里加上-RunAsAdministrator参数,或者确保创建PSSession时用的是管理员身份

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 10:15:17