![](/img/trans.png)
[英]How to run sudo command via ssh by powershell in cmd.exe
[英]Run command in cmd.exe using PowerShell
我正在打开cmd。 我指定了一个路径并希望运行一个存储在 createDBsQuery 文件中的命令,该文件存储在$createdbs
变量中。
我的疑问是:我们可以发送 cd...(path) 然后我想运行的命令,同时使用 PowerShell。 如果上述情况是可能的,我传递参数的方式是否正确?
我的代码:
$somefile = "C:\ProgramFiles\site.txt"
$createdbs = "C:\PowerShell\createDBsQuery"
Start-Process cmd.exe -Args '/c cd C:\ProgramFiles\Infor\Tools',$createdbs -RedirectStandardOutput $somefile
在您的 CMD 中,输入“PowerShell”。 这应该会将您转至最新版本的 Windows PowerShell。 这可以达到 5.1 版。 如果您已经安装了 .NET Core,则可以输入“Pwsh”。 这将使您进入较新的 PowerShell 版本,即 6.2。 您的提示也应该有一个“PS [...]>”前缀。
PowerShell 与任何 shell 一样,可以直接、同步地执行控制台应用程序,并将应用程序的标准流连接到 PowerShell 的流。
如果您想在新窗口中运行程序,请仅使用Start-Process
[1] ; 还要注意Start-Process
默认是异步的。
下面展示了如何直接从 PowerShell 同步运行createDbsQuery
命令,使用 PowerShell 临时更改工作目录并将命令的输出捕获到文件中:
$somefile = "C:\ProgramFiles\site.txt"
$createdbs = "C:\PowerShell\createDBsQuery"
# Change to the directory required by the $createdbs script.
# and save the current directory.
Push-Location 'C:\ProgramFiles\Infor\Tools'
# Invoke the script and capture its stdout out in file $somefile
# Since the command path is stored in a variable, `& ` is needed to
# invoke it.
# Note that in Windows PowerShell `>` creates Unicode (UTF-16LE) files by default.
# In PowerShell [Core] 6+, BOM-less UTF-8 is used.
# To control the encoding, pipe to Set-Content; e.g.:
# & $createdbs | Set-Content $someFile -Encoding Utf8
& $createdbs > $somefile
# Restore the previous directory.
Pop-Location
如您所见,没有必要涉及cmd.exe
(但如果$createdbs
恰好是一个批处理文件,( *.bat
, *.cmd
), cmd.exe
将隐式执行它),鉴于 PowerShell,如一个外壳本身,提供与cmd.exe
相同的功能 - 以及更多。
[1] 还有一个-NoNewWindow
选项,但很少需要它,因为直接调用不仅默认提供同步、同窗口执行,而且还将被调用程序的标准输出流连接到 PowerShell 的,启用输出捕获和重定向. -NoNewWindow
是主要有用-Wait
暂时故障排除Start-Process
意味着在新的窗口中运行的呼叫,如果窗口关闭(太)很快由于错误,看看有什么输出产生那里。
如果确实需要运行 cmd,同时已经使用 PowerShell,这将满足您的目的:
$somefile = "C:\ProgramFiles\site.txt"
$createdbs = "C:\PowerShell\createDBsQuery"
Start-Process cmd.exe -ArgumentList "/c cd C:\ProgramFiles\Infor\Tools & $createdbs" -RedirectStandardOutput $somefile
您可以创建一个包含所有必要参数的 powershell .ps1 脚本文件,并从 CMD 调用它,例如,如下所示。
powershell -command "&{"C:\temp\script.ps1"}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.