Powershell:与&;在脚本块中

Powershell:与&;在脚本块中,powershell,powershell-remoting,Powershell,Powershell Remoting,我在运行以下命令时遇到一个问题 $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

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

$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会话中的变量不会传输到使用
Invoke命令创建的会话中

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

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

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

您还可以将其与飞溅技术结合使用。例如:
@使用: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'