2010-08-12 57 views
3

我有一套我想運行的命令,並對結果進行一些返回碼檢查,所以我覺得很容易將它們放入數組中執行。Powershell:使用數組中的參數調用exe文件?

讓我們這個作爲一個例子:

C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section system.webServer/webdav/authoring /enabled:true /commit:apphost 

現在,當我把它放到我的數組沒有任何引號一下就解釋爲命令,執行命令和結果被寫入陣列:

$commands = @() 
$commands += C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section system.webServer/webdav/authoring /enabled:true /commit:apphost 

當我使用引號將它作爲字符串放入數組中時,試圖執行它不起作用。

PS> $commands = @() 
PS> $commands += "C:\windows\system32\inetsrv\AppCmd.exe set config ""Default Web Site/"" /sectio n:system.webServer/webdav/authoring /enabled:true /commit:apphost" 
PS> $commands[0] 
C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section:system.webServer/webdav/authoring /enabled:true /commit:apphost 
PS> & $commands[0] 
The term 'C:\windows\system32\inetsrv\AppCmd.exe set config "Default Web Site/" /section:system.webServer/webdav/authoring /enabled:true /commit:apphost' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. 
     At line:1 char:2 
     + & <<<< $commands[0] 
      + CategoryInfo   : ObjectNotFound: (C:\windows\syst.../commit:apphost:String) [], CommandNotFoundException 
      + FullyQualifiedErrorId : CommandNotFoundException 

那麼,如何正確地我把這個命令到一個數組,隊列或什麼最適合這樣我就可以在適當的時候執行呢?

回答

3

當您使用呼叫運營商&後面的字符串必須僅命名要執行的命令 - 而不是任何參數。隨着已配置的內容,你可以使用調用-表達,而不是如:

約調用,表達
iex $command[0] 

一個警告,要小心,如果任何輸入來自用戶,因爲它可以被用來注入惡意指令的使用這個命令如:

Read-Host "Enter commit value" 
Enter commit value: apphost; remove-item c:\ -r -force -ea 0 -confirm:0 # 
+0

啊,invoke-expression是。我試過invoke-command。猜猜我下次更好的閱讀文檔。謝謝! – 2010-08-13 09:11:13

0

嗯,我晚了一年來的一方,但你也可以這樣做:

新別名-name猴 - 值「$ ENV:WINDIR \ SYSTEM32 \ INETSRV \ APPCMD .exe「

相關問題