【问题标题】:Problems using local variables in a remote commands在远程命令中使用局部变量的问题
【发布时间】:2015-03-04 01:04:55
【问题描述】:

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

这行得通:

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 filesystems


    【解决方案1】:

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

    1.将它们与-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.将它们与-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-variable 范围以使其更容易:

    $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 上阅读更多相关信息

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 2021-05-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 2016-12-16
      • 1970-01-01
      • 2010-10-03
      • 2011-03-19
      相关资源
      最近更新 更多