繁体   English   中英

如何在 CMD 中运行 PowerShell

[英]How to run PowerShell in CMD

我正在尝试在 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、函数、

我该如何解决这个问题?

您需要将参数与文件路径分开:

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

另一个可以使用 File 参数和位置参数简化语法的选项:

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

我想在 Shay Levy 的正确答案中添加以下内容:如果您创建一个小批处理脚本run.cmd来启动您的 powershell 脚本,您可以让您的生活更轻松:

运行命令

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

将它放在与SQLExecutor.ps1相同的路径中,从现在开始,您只需双击run.cmd即可运行它。


笔记:

  • 如果您需要 run.cmd 批处理中的命令行参数,只需将它们作为%1 ... %9 (或使用%*传递所有参数)传递给 powershell 脚本,即
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • 变量batchPath包含批处理文件本身的执行路径(这是表达式%~dp0的用途)。 因此,您只需将 powershell 脚本放在与调用批处理文件相同的路径中。

试试吧:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM