如何让PowerShell保持命令窗口打开?

时间:2012-02-11 21:39:17

标签: windows shell powershell

当我在PowerShell上运行程序时,它打开一个新窗口,在我看到输出之前,窗口关闭。如何使PowerShell保持此窗口打开?

5 个答案:

答案 0 :(得分:9)

尝试做:

start-process your.exe -NoNewWindow

如果需要,也添加-Wait

答案 1 :(得分:5)

OP似乎对答案感到满意,但是在执行程序后它并没有保持新窗口打开,这是他似乎要问的问题(以及我正在寻找的答案)。所以,经过一些研究后,我提出了:

Start-Process cmd "/c `"your.exe & pause `""

答案 2 :(得分:3)

几周前,我正在解决类似的问题。如果你不想使用& (& '.\program.exe')然后你可以使用start process并通过start process读取输出(你明确地读取输出)。

只需将其作为单独的PS1文件 - 例如(或宏):

param (
    $name,
    $params
)

$process = New-Object System.Diagnostics.Process
$proInfo = New-Object System.Diagnostics.ProcessStartInfo
$proInfo.CreateNoWindow = $true
$proInfo.RedirectStandardOutput = $true
$proInfo.RedirectStandardError = $true
$proInfo.UseShellExecute = $false
$proInfo.FileName = $name
$proInfo.Arguments = $params
$process.StartInfo = $proInfo

#Register an Action for Error Output Data Received Event
Register-ObjectEvent -InputObject $process -EventName ErrorDataReceived -action {
    foreach ($s in $EventArgs.data) { Write-Host $s -ForegroundColor Red }
} | Out-Null

#Register an Action for Standard Output Data Received Event
Register-ObjectEvent -InputObject $process -EventName OutputDataReceived -action {
    foreach ($s in $EventArgs.data) { Write-Host $s -ForegroundColor Blue }
} | Out-Null

$process.Start() | Out-Null
$process.BeginOutputReadLine()
$process.BeginErrorReadLine()
$process.WaitForExit()

然后称之为:

.\startprocess.ps1 "c:\program.exe" "params"

您还可以轻松重定向输出或实施某种超时,以防您的应用程序冻结......

答案 3 :(得分:2)

如果程序是使用cmd /c foo.cmd命令启动的批处理文件(.cmd或.bat扩展名),只需将其更改为cmd /k foo.cmd并执行程序,但提示保持打开状态。

如果程序不是批处理文件,请将其包装在批处理文件中,并在其末尾添加pause命令。要将程序包装在批处理文件中,只需将命令放在文本文件中,并为其指定.cmd扩展名。然后执行它而不是exe。

答案 4 :(得分:0)

使用Startprocess并在$ arguments脚本块中,您可以放置​​一个Read-Host

$arguments = {
    "Get-process"
    "Hello"
    Read-Host "Wait for a key to be pressed"
  }
Start-Process powershell -Verb runAs -ArgumentList $arguments