2013-05-08 52 views
26

我試圖在cmd命令行中運行PowerShell腳本。有人給我一個例子,它的工作原理:如何在CMD中運行PowerShell

powershell.exe -noexit "& 'c:\Data\ScheduledScripts\ShutdownVM.ps1'" 

但問題是我的PowerShell腳本有輸入參數,所以我試過,但不起作用:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' " 

的錯誤是:

術語'D:\ Work \ SQLExecutor.ps1 -gettedServerName「MY-PC」'不被識別爲cmdlet的名稱,函數,

等待幫助!謝謝!

+2

您確定要使用-noexit嗎?這意味着當你的腳本完成時,shell會掛起,可能會阻塞CMD中批處理文件的執行。 – x0n 2013-05-08 15:56:09

回答

51

您需要的參數從文件路徑分開:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'" 

可使用File參數和位置參數緩解語法另一種選擇:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC" 
+0

非常感謝! – XiaoYao 2013-05-09 02:15:56

4

嘗試只:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" 
0

我想添加以下內容給Shay Levy的正確答案: 如果你創建了一個小批處理腳本run.cmd啓動您的PowerShell腳本可以讓您的生活更輕鬆:

@echo off & setlocal 
set batchPath=%~dp0 
powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" "MY-PC" 

把它放在相同的路徑SQLExecutor.ps1,從現在起,您可以通過run.cmd只需雙擊運行它。如果您需要命令行參數,只需將它們作爲%1 ... %9傳遞給powershell腳本(在run.cmd批處理內)。