我正在打开cmd。我指定了一条路径,并希望运行存储在$createdbs
变量中的createDBsQuery文件中的命令。
我的疑问是:我们可以同时使用PowerShell发送cd ...(path),然后发送我要运行的命令吗?如果上述情况可行,我传递参数的方式是否正确?
我的代码:
$somefile = "C:\ProgramFiles\site.txt"
$createdbs = "C:\PowerShell\createDBsQuery"
Start-Process cmd.exe -Args '/c cd C:\ProgramFiles\Infor\Tools',$createdbs -RedirectStandardOutput $somefile
答案 0 :(得分:1)
在CMD中,输入“ PowerShell”。这将使您进入Windows PowerShell的最新版本。最高可以是5.1版。如果您已经安装了.NET Core,则可以输入“ Pwsh”。这将使您进入较新的PowerShell版本,即6.2。 您的提示还应该带有“ PS [...]>”前缀。
答案 1 :(得分:1)
PowerShell与任何Shell一样,可以直接同步执行控制台应用程序,而将应用程序的标准流连接到PowerShell的流。
如果要在新窗口中运行程序 [1] ,请仅使用Start-Process
;还请注意,Start-Process
默认为异步。
以下内容向您展示如何使用PowerShell临时更改工作目录并将命令的输出捕获到文件中,从而从PowerShell直接并同步地运行createDbsQuery
命令:
$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
,{{ 1}}),*.cmd
将隐式执行它),因为PowerShell作为本身的外壳提供了与cmd.exe
相同的功能-还有许多更多。
[1]还有一个cmd.exe
选项,但很少使用,因为直接调用不仅默认情况下使您在同步,同窗口中执行,而且还可以连接被调用程序的标准输出-NoNewWindow
主要用于-NoNewWindow
,用于临时进行故障排除 -Wait
的调用,该调用打算在新窗口中运行,{由于发生错误,windows很快关闭(过),以查看那里产生了什么输出。
答案 2 :(得分:0)
如果确实已经在使用PowerShell的情况下运行cmd,这将达到您的目的:
$somefile = "C:\ProgramFiles\site.txt"
$createdbs = "C:\PowerShell\createDBsQuery"
Start-Process cmd.exe -ArgumentList "/c cd C:\ProgramFiles\Infor\Tools & $createdbs" -RedirectStandardOutput $somefile
答案 3 :(得分:-1)
您可以创建具有所有必要参数的powershell .ps1脚本文件,并从CMD进行调用,例如,如下所示。
powershell -command "&{"C:\temp\script.ps1"}"