PowerShell:脚本块中的“&”问题

10

当我运行以下命令时,遇到了一个问题

$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
2个回答

12

在 PowerShell 会话中的变量不会传递到使用 Invoke-Command 创建的会话。

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

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

4

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

您还可以与splatting技术一起使用。例如:@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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接