使用 Invoke-Command 修改 ScriptBlock 内的远程变量

Modifying remote variables inside ScriptBlock using Invoke-Command

是否可以修改远程变量?我正在尝试执行以下操作:

$var1 = ""
$var2 = ""

Invoke-Command -ComputerName Server1 -ScriptBlock{
$using:var1 = "Hello World"
$using:var2 = "Goodbye World"
}

当我尝试此操作时出现错误:

The assignment expression is not valid.  The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property.

很明显,使用这种方法行不通,但是我可以采用其他方法吗?我需要在远程和本地范围内使用和修改这些变量

您尝试做的根本行不通:

调用者作用域中的变量的$using:引用在执行的脚本块中会话(例如远程,通过Invoke-Command -ComputerName,如您的情况):

  • 不是变量对象的引用(对整个变量),

  • 但是扩展到变量的,并且你根本不能给.

在手头的例子中,$using:var1 在您的脚本块中实际上变成了 ""(当 Invoke-Command 被调用),并且像 "" = "Hello world" 这样的东西不能工作。

截至撰写本文时,概念性帮助主题 about_Remote_Variables doesn't yet mention the above, but an update is imminent

有关背景信息,请参阅


至于可能的解决方案

让你的脚本块输出感兴趣的值,然后分配给局部变量,如.

所示

所以你试图做的是行不通的。但这里有一个解决方法。

将您想要的数据 return 放入哈希表中,然后捕获结果并枚举它们并将值放入变量中。

$var1 = ""
$var2 = ""

$Reponse = Invoke-Command -ComputerName Server1 -ScriptBlock{
    $Stuff1 = "Hey"
    $Stuff2 = "There"
    Return @{
        var1 = $Stuff1
        var2 = $Stuff2
    }
}

$Reponse.GetEnumerator() | %{
    Set-Variable $_.Key -Value $_.Value
}

$var1
$var2

这将return

Hey
There