在远程命令中使用局部变量的问题

Problems using local variables in a remote commands

我需要编写一个脚本来接收变量并在远程系统上进行共享。

这个有效:

Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create("C:\test","test",0)}

但这不是:

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)}

我需要一种方法来以某种方式传递这些值。

远程会话无法读取您的本地变量,因此您需要将它们与您的命令一起发送。这里有几个选项。在 PowerShell 2.0 中,您可以:

1.Pass 它们与 -ArgumentList 一起使用 $arg[i]

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock {$a = [WMICLASS]"Win32_Share"; $a.Create($args[0],$args[1],0)} -ArgumentList $sharepath, $sharename

2.Pass 它们与 -ArgumentList 并在脚本块中使用 param() 来定义参数

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { param($sharepath, $sharename) $a = [WMICLASS]"Win32_Share"; $a.Create($sharepath,$sharename,0)} -ArgumentList $sharepath, $sharename

在 PowerShell 3.0 中,引入了 using 变量范围以使其更容易:

$sharepath = "C:\test"
$sharename = "test"
Invoke-Command -ComputerName server -ScriptBlock { $a = [WMICLASS]"Win32_Share"; $a.Create($using:sharepath,$using:sharename,0)}

您可以在 about_Remote_Variables @ TechNet

上阅读更多相关信息