【问题标题】:Powershell: Issue with & in scriptblockPowershell:脚本块中的&问题
【发布时间】:2013-07-26 12:07:13
【问题描述】:

我在运行以下命令时遇到问题

$x =  "c:\Scripts\Log3.ps1"
$remoteMachineName = "172.16.61.51"
Invoke-Command -ComputerName $remoteMachineName  -ScriptBlock {& $x}

The expression after '&' in a pipeline element produced an invalid object. It must result in a command name, script
block or CommandInfo object.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : BadExpression
    + PSComputerName        : 172.16.61.51

如果我不使用$x 变量,则不会出现问题

Invoke-Command -ComputerName $remoteMachineName  -ScriptBlock {& 'c:\scripts\log3.ps1'}

    Directory: C:\scripts


Mode                LastWriteTime     Length Name                                  PSComputerName
----                -------------     ------ ----                                  --------------
-a---         7/25/2013   9:45 PM          0 new_file2.txt                         172.16.61.51

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:

    PowerShell 会话中的变量不会转移到使用 Invoke-Command 创建的会话中

    您需要使用-ArgumentList 参数将变量发送到您的命令,然后使用$args 数组在脚本块中访问它们,这样您的命令将如下所示:

    Invoke-Command -ComputerName $remoteMachineName  -ScriptBlock {& $args[0]} -ArgumentList $x
    

    【讨论】:

      【解决方案2】:

      如果您在脚本块中使用变量,则需要添加修饰符 using:。否则 Powershell 会在脚本块中搜索 var 定义。

      您也可以将它与喷溅技术一起使用。例如:@using:params

      像这样:

      # C:\Temp\Nested.ps1
      [CmdletBinding()]
      Param(
       [Parameter(Mandatory=$true)]
       [String]$Msg
      )
      
      Write-Host ("Nested Message: {0}" -f $Msg)
      

      # C:\Temp\Controller.ps1
      $ScriptPath = "C:\Temp\Nested.ps1"
      $params = @{
          Msg = "Foobar"
      }
      $JobContent= {
          & $using:ScriptPath @using:params
      }
      Invoke-Command -ScriptBlock $JobContent -ComputerName 'localhost'
      

      【讨论】:

        猜你喜欢
        • 2017-10-23
        • 2015-07-07
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-17
        • 2018-02-22
        • 2013-12-07
        相关资源
        最近更新 更多