windows 通过 PowerShell 运行 .cmd 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20423424/
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 11:09:04  来源:igfitidea点击:

Run a .cmd file through PowerShell

windowspowershellcmd

提问by Declan McNulty

I am trying to run a .cmd file on a remote server with PowerShell.

我正在尝试使用 PowerShell 在远程服务器上运行 .cmd 文件。

In my .ps1 script I have tried this:

在我的 .ps1 脚本中,我试过这个:

C:\MyDirectory\MyCommand.cmd

It results in this error:

它导致此错误:

C:\MyDirectory\MyCommand.cmd is not recognized as the name of a cmdlet,
function, script file, or operable program.

And this

和这个

Invoke-Command C:\MyDirectory\MyCommand.cmd

results in this error:

导致此错误:

Invoke-Command : Parameter set cannot be resolved using the specified named
parameters.

I do not need to pass any parameters to the PowerShell script. What is the correct syntax that I am looking for?

我不需要将任何参数传递给 PowerShell 脚本。我正在寻找的正确语法是什么?

采纳答案by alroc

Invoke-Itemwill look up the default handler for the file type and tell it to run it.

Invoke-Item将查找文件类型的默认处理程序并告诉它运行它。

It's basically the same as double-clicking the file in Explorer, or using start.exe.

它与在资源管理器中双击文件或使用start.exe.

回答by mirabilos

Try invoking cmd /c C:\MyDirectory\MyCommand.cmd– that should work.

尝试调用cmd /c C:\MyDirectory\MyCommand.cmd- 这应该有效。

回答by Gustavo A Sanchez

Go to C:\MyDirectory and try this:

转到 C:\MyDirectory 并尝试以下操作:

.\MyCommand.cmd

回答by Armand G.

To run or convert batch files to PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, for example, deletefolders.ps1.

要将批处理文件运行或转换为 PowerShell(特别是如果您希望使用证书对所有计划任务脚本进行签名),我只需创建一个 PowerShell 脚本,例如,deletefolders.ps1。

Input the following into the script:

在脚本中输入以下内容:

cmd.exe /c "rd /s /q C:\#TEMP\test1"

cmd.exe /c "rd /s /q C:\#TEMP\test2"

cmd.exe /c "rd /s /q C:\#TEMP\test3"

*Each command needs to be put on a new line, calling cmd.exe again.

*每个命令都需要换行,再次调用cmd.exe。

This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.

该脚本现在可以签名并从 PowerShell 运行,直接将命令输出到命令提示符 / cmd。

It is a much safer way than running batch files!

这是比运行批处理文件更安全的方法!