2014-09-19 95 views
0

我正在腳本化任務以定期遠程重新啓動一些服務器應用程序池。我正在使用Invoke-Command,如下所示:Powershell調用命令查詢

Invoke-Command -ComputerName $server {Restart-WebItem "IIS:\AppPools\DefaultAppPool"} 

這個工作就好了;但是,如果我參數化應用程序池如下

$appPool = "IIS:\AppPools\DefaultAppPool" 
Invoke-Command -ComputerName $server {Restart-WebItem $appPool} 

它失敗

Unexpected object type. 
Parameter name: pspath 

我認爲這僅僅是一個語法問題,但我不知道是什麼。

回答

1

遠程主機$ appPool將不存在。 如果您使用PS V3可以用using:關鍵詞前綴的變量 - >

$appPool = "IIS:\AppPools\DefaultAppPool" 
Invoke-Command -ComputerName $server {Restart-WebItem $using:appPool} 

前3版本,你必須使用-argumentList參數

+0

優秀的使用$語法工作。奇怪的是,我的印象是,在命令被遠程執行之前,本地變量已經解決了。 我正在使用-ArgumentList獲取相同的錯誤消息。 – 2014-09-19 13:18:07

+0

@KevinRoche nope,這就是爲什麼'-argumentlist'用於:「提供命令中局部變量的值。在命令在遠程計算機上運行之前,命令中的變量被這些值替換。」 – 2014-09-19 13:21:36

+0

剛剛用-ArgumentList嘗試了一些測試,但我錯過了一些東西。這個函數的-PSPath參數是一個字符串數組,所以我嘗試了{Restart-WebItem} -ArgumentList(,$ appPool)和{Restart-WebItem} -ArgumentList $ appPool - 與原始相同的錯誤。什麼是正確的語法? – 2014-09-19 13:47:07