2013-05-08 105 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批处理内)。