Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get PowerShell to keep a command window open?

When I run a program on PowerShell it opens a new window and before I can see the output, the window closes. How do I make it so PowerShell keeps this window open?

like image 802
Erman Avatar asked Feb 11 '12 21:02

Erman


People also ask

How do I stop PowerShell from closing after running a script?

PowerShell's built-in exit keyword allows you to terminate scripts without closing your PowerShell session.

How do I open a Command Prompt in PowerShell?

Press Ctrl + Shift + Esc to open the Task Manager. Click the File tab on the top-left corner and select Run new task. In the next window, type Powershell and click OK to open the Command prompt.


3 Answers

Try doing:

start-process your.exe -NoNewWindow

Add a -Wait too if needed.

like image 177
manojlds Avatar answered Oct 13 '22 17:10

manojlds


The OP seemed satisfied with the answer, but it doesn't keep the new window open after executing the program, which is what he seemed to be asking (and the answer I was looking for). So, after some more research, I came up with:

Start-Process cmd "/c `"your.exe & pause `""
like image 30
Cary Avatar answered Oct 13 '22 18:10

Cary


I was solving a similar problem few weeks ago. If you don't want to use & (& '.\program.exe') then you can use start process and read the output by start process (where you read the output explicitly).

Just put this as separate PS1 file - for example (or to macro):

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()

And then call it like:

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

You can also easily redirect output or implement some kind of timeout in case your application can freeze...

like image 4
Tomas Panik Avatar answered Oct 13 '22 16:10

Tomas Panik