windows 如何在 CMD 中运行 PowerShell

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16436405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:29:29  来源:igfitidea点击:

How to run PowerShell in CMD

windowspowershellbatch-filecmd

提问by XiaoYao

I'm trying to run a PowerShell script inside cmd command line. Someone gave me an example and it worked:

我正在尝试在 cmd 命令行中运行 PowerShell 脚本。有人给了我一个例子,它奏效了:

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

But the problem is my PowerShell script has input parameters, so I tried, but it doesn't work:

但问题是我的 PowerShell 脚本有输入参数,所以我尝试了,但它不起作用:

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

The error is:

错误是:

The term 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' is not recognized as the name of a cmdlet, function,

术语 'D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC" ' 未被识别为 cmdlet、函数、

How can I fix this problem?

我该如何解决这个问题?

回答by Shay Levy

You need to separate the arguments from the file path:

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

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

Another option that may ease the syntax using the File parameter and positional parameters:

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

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

回答by Matt

I'd like to add the following to Shay Levy's correct answer: You can make your life easier if you create a little batch script run.cmdto launch your powershell script:

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

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

Put it in the same path as SQLExecutor.ps1and from now on you can run it by simply double-clicking on run.cmd.

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



Note:

笔记:

  • If you require command line arguments inside the run.cmd batch, simply pass them as %1... %9(or use %*to pass all parameters) to the powershell script, i.e.
    powershell.exe -noexit -file "%batchPath%SQLExecutor.ps1" %*

  • The variable batchPathcontains the executing path of the batch file itself (this is what the expression %~dp0is used for). So you just put the powershell script in the same path as the calling batch file.

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

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

回答by CB.

Try just:

试试吧:

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