Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Function 调用命令执行的函数中的变量不可见_Function_Powershell_Variables_Scope_Invoke Command - Fatal编程技术网

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}