调用Invoke-Command执行嵌套ScriptBlock时出现Invoke方法未找到错误
报错原因
- PowerShell 跨远程会话传递
ScriptBlock类型对象时,默认会被序列化为纯字符串,你在远程执行上下文里通过$using:ScriptBlock拿到的实际是字符串类型,不是脚本块,自然不存在Invoke方法,触发对应报错。 - 现有代码存在额外错误:
Invoke-Command的-Computer参数写死为pv3039,没有使用函数传入的$Computer参数,会导致指定其他远程主机时参数不生效。
解决方案
将远程侧拿到的序列化后的字符串重新转换为脚本块即可,同时修复硬编码的计算机名问题,修复后的完整代码如下:
function nice_invoke { param( [string]$Computer, [scriptblock]$ScriptBlock ) Set-PSDebug -Trace 0 $cwd = (Get-Location).Path Write-Host "Local current directory: $cwd" $wrapper = { $target = $using:cwd if (-not (Test-Path "$target")) { Write-Host "ERROR: Directory doesn't exist on remote host" exit 1 } else { Set-Location $target } # 把序列化后的字符串转回脚本块 $sb = [scriptblock]::Create($using:ScriptBlock) # 执行脚本块,&调用更符合PowerShell编码习惯,也可替换为$sb.Invoke() & $sb | Out-Host } # 替换硬编码的计算机名,使用传入的参数 Invoke-Command -Computer $Computer -ScriptBlock $wrapper }
修复后你原有调用方式不需要修改,可直接正常执行。
内容的提问来源于stack exchange,提问作者pico
相关产品推荐
相关产品推荐

