Function 调用命令执行的函数中的变量不可见
有人能帮我得到下面的代码工作吗Function 调用命令执行的函数中的变量不可见,function,powershell,variables,scope,invoke-command,Function,Powershell,Variables,Scope,Invoke Command,有人能帮我得到下面的代码工作吗 $ab = "1" function test { $script:ab = "c" } invoke-command -ComputerName localhost ${function:test} $ab 通过invoke命令运行上述函数后,我希望看到$ab的值“c”注意:${function:test}是PowerShell名称空间表示法的一个不寻常的实例,相当于 (获取项函数:test).ScriptBlock;i、 例如,它引用函数体test,作为
$ab = "1"
function test {
$script:ab = "c"
}
invoke-command -ComputerName localhost ${function:test}
$ab
通过invoke命令运行上述函数后,我希望看到$ab的值“c”注意:${function:test}
是PowerShell名称空间表示法的一个不寻常的实例,相当于(获取项函数:test).ScriptBlock
;i、 例如,它引用函数体test
,作为脚本块
使用-ComputerName
参数时,Invoke命令
使用远程处理来执行指定的脚本块,即使目标计算机是同一台机器(localhost
或
)
远程执行的代码在不同的进程中运行,无法访问调用方的变量
因此:
- 如果目标是本地执行,只需省略
参数;同样,在这种情况下,您只需运行-ComputerName
甚至只是${function:test}
:test
$ab = "1" function test { $script:ab = "c" } test # shorter equivalent of: Invoke-Command ${function:test}
- 对于远程执行,从远程执行的脚本块输出所需的新值,并将其分配给调用者作用域中的
:$ab
$ab = "1" function test { "c" } # Note: "c" by itself implicitly *outputs* (returns) "c" $ab = Invoke-Command -ComputerName localhost ${function:test}