PowerShell中使用Invoke-SSHCommand如何向ScriptBlock传递参数
问题原因
- 你调用的
Invoke-SshCommand属于Posh-SSH第三方模块,并不支持原生PowerShellInvoke-Command自带的-ArgumentList参数,参数不存在才会触发绑定报错。
解决方法
方法1:使用$using:作用域引用本地变量(推荐,适配Posh-SSH v2.1及以上版本)
Posh-SSH已原生支持PowerShell的$using作用域标记,可以直接在脚本块内引用本地会话的变量,不需要额外传参:
param ( [Parameter(mandatory=$true)][string]$param1 ) Remove-SshSession -ErrorAction SilentlyContinue # 建立SSH会话(注意补充你的认证逻辑,比如密码/密钥参数) $session = New-SshSession -ComputerName $myServer $result = Invoke-SshCommand -Session $session -ScriptBlock { /root/scripts/Test.sh $using:param1 }
方法2:命令字符串拼接(适配所有Posh-SSH版本)
如果你的模块版本较低不支持$using,可以提前拼接好完整的bash命令字符串,直接传给-Command参数即可:
注意要对参数内的特殊字符做转义,避免bash解析异常或者注入风险
param ( [Parameter(mandatory=$true)][string]$param1 ) Remove-SshSession -ErrorAction SilentlyContinue $session = New-SshSession -ComputerName $myServer # 转义参数内的单引号,再拼接完整命令 $escapedParam = $param1.Replace("'", "'\''") $fullBashCmd = "/root/scripts/Test.sh '$escapedParam'" $result = Invoke-SshCommand -Session $session -Command $fullBashCmd
注意事项
- 尽量复用已经建立的
$session对象调用命令,不要重复指定-ComputerName,避免重复建连开销 - 如果参数包含空格、特殊符号,务必做转义处理,避免bash命令执行不符合预期
内容的提问来源于stack exchange,提问作者greenapple
相关产品推荐
相关产品推荐

