2012-07-31 100 views
1

我需要從本地腳本執行遠程計算機上的Powershell腳本。問題是,我不知道遠程腳本的路徑或文件名,直到runitime。帶腳本名稱變量的Powershell調用命令

我試過下面一行在我的本地腳本:

Invoke-Command -ComputerName $TargetServer -ScriptBlock { & ($TargetMSI) '$MSI' 'C:\Program Files (x86)\Vasanta.Int.MIS' 'Dev' } 

問題是這樣返回錯誤:後「&」的表達在管線元件產生的無效的對象。

如果用硬編碼的字符串文字替換$ TargetMSI,那麼它工作正常。

任何人都可以告訴我我需要改變什麼嗎?

回答

2

當您在v2中調用命令時,沒有直接的方法將變量傳遞給scriptblock。您需要在scriptblock組合中使用-ArgumentList + param():

Invoke-Command -ScriptBlock { param ($TargetMSI, $MSI) & $TargetMSI '$MSI' } -ArgumentList $TargetMSI, $MSI 

這是在v3中用$ using:localvariable語法修復/改進的。

+0

非常感謝Batek。我現在工作的代碼行如下所示:Invoke-Command -ComputerName $ TargetServer -ScriptBlock {param($ TargetMSI,$ MSI,$ InstallPath,$ Environment)&$ TargetMSI $ MSI $ InstallPath $ Environment} -ArgumentList $ TargetMSI,$ MSI,$ InstallPath,$ Environment – 2012-07-31 12:00:53