2013-07-26 56 views
4

我面對的一個問題,當我運行下面的命令PowerShell的:問題與及在腳本塊

$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 

回答

6

變量在你的PowerShell會話是不會轉移到創建的會話中Invoke-Command

您需要使用-ArgumentList參數將變量-r命令,然後用$args數組訪問它們在腳本塊使您的命令看起來像:

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

如果你需要添加改性劑using:一個腳本塊內變量的工作。否則,Powershell將搜索腳本塊內的var定義。

你也可以使用它與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'