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

调用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:15:02