使用 Invoke-Command 修改 ScriptBlock 中的远程变量 [英] Modifying remote variables inside ScriptBlock using Invoke-Command
本文介绍了使用 Invoke-Command 修改 ScriptBlock 中的远程变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以修改远程变量?我正在尝试执行以下操作:
Is it possible to modify remote variables? I am trying to do something like the following:
$var1 = ""
$var2 = ""
Invoke-Command -ComputerName Server1 -ScriptBlock{
$using:var1 = "Hello World"
$using:var2 = "Goodbye World"
}
当我尝试此操作时出现错误:
When I try this I get the error:
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.
很明显,使用这种方法是行不通的,但是我可以采取其他任何方法吗?我需要在远程和本地范围内使用和修改这些变量
So obviously, it doesn't work using this method, but are there any other approaches I could take? I need to use and modify those variables in both a remote and local scope
推荐答案
所以你尝试做的事情是行不通的.但这里有一个解决方法.
So what you are trying to do wont work. But here is a work around.
将您想要返回的数据放入哈希表中,然后捕获结果并枚举它们并将值放入变量中.
Place your data you want returned into a hashtable and then capture the results and enumerate over them and place the value into the variables.
$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
这将返回
Hey
There
这篇关于使用 Invoke-Command 修改 ScriptBlock 中的远程变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文