Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make Powershell run a batch file and then stay open?

Tags:

For example; with the old command prompt it would be:

cmd.exe /k mybatchfile.bat 
like image 431
John Richardson Avatar asked Aug 18 '08 08:08

John Richardson


People also ask

How do I keep the shell window open after running a PowerShell script?

Global Fix: Change your registry key by adding the -NoExit switch to always leave the PowerShell Console window open after the script finishes running.

How do I stop command prompt from closing after batch file?

If you want the command prompt cmd widnow to stay open after executing the last command in batch file –you should write cmd /k command at the end of your batch file. This command will prevent the command prompt window from closing and you'll get the prompt back for giving more commands in the cmd window.


2 Answers

Drop into a cmd instance (or indeed PowerShell itself) and type this:

powershell -? 

You'll see that powershell.exe has a "-noexit" parameter which tells it not to exit after executing a "startup command".

like image 131
Matt Hamilton Avatar answered Oct 15 '22 18:10

Matt Hamilton


When running PowerShell.exe just provide the -NoExit switch like so:

PowerShell -NoExit -File "C:\SomeFolder\SomePowerShellScript.ps1"  PowerShell -NoExit -Command "Write-Host 'This window will stay open.'" 

Or if you want to run a file and then run a command and have the window stay open, you can do something like this:

PowerShell -NoExit "& 'C:\SomeFolder\SomePowerShellScript.ps1'; Write-Host 'This window will stay open.'" 

The -Command parameter is implied if not provided, and here we use the & to call the PowerShell script, and the ; separates the PowerShell commands.

Also, at the bottom of my blog post I show a quick registry change you can make in order to always have PowerShell remain open after executing a script/command, so that you don't need to always explicitly provide the -NoExit switch all the time.

like image 27
deadlydog Avatar answered Oct 15 '22 17:10

deadlydog