I'm running the following script in Powershell:
start powershell @'
$Host.UI.RawUI.BackgroundColor = \"red\"
$Host.UI.RawUI.ForegroundColor = \"black\"
[console]::WindowWidth=100;
[console]::WindowHeight=30;
Clear-Host
cd application1\backend
npm run start
'@
start powershell @'
$Host.UI.RawUI.BackgroundColor = "blue"
$Host.UI.RawUI.ForegroundColor = "white"
[console]::WindowWidth=100;
[console]::WindowHeight=30;
Clear-Host
cd application2\backend
npm run start
'@
start powershell @'
$Host.UI.RawUI.BackgroundColor = "yellow"
$Host.UI.RawUI.ForegroundColor = "black"
[console]::WindowWidth=100;
[console]::WindowHeight=30;
Clear-Host
cd application3\backend
npm run start
'@
This opens 3 new Powershell terminals and runs 3 different node applications (one per terminal).
It works fine except that when I kill the node application by hitting ctrl-c, it closes the terminal.
How can I keep the terminal open after hitting ctrl-c such that I can interact with it as I would a normal Powershell terminal that I opened manually?
Things I've tried:
- Added
Read-Hostto the end of each script block. This doesn't work because while it awaits user input after hitting ctrl-c (thus not closing the terminal), it closes the terminal as soon as I enter input. - Added
[console]::TreatControlCAsInput = $trueto the beginning of each script block. This prevents ctrl-c from working at all, so I can't terminate the node applications. - Added
-NoExitafterstart powershellon each script block but this just throws an error.
Any insight would be much appreciated. Thanks!
I'm on Windows 10.
UPDATE: I was offered this answer: Powershell Start-Process - can I make it leave the windows open?, as a potential solution to my problem but it doesn't work. It offers three solutions:
-
One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
Running each script manually from its own powershell terminal defeats the purpose, and adding the -NoExit flag, like I said, just gives me an error. Perhaps there's a different syntax/format the -NoExit flag fits into in my case?
-
Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
Again, like I said, I tried this and it doesn't work because 1) the terminal is already paused due to the running of the node application and 2) even if I were to unpause it with ctrl-c, the next key I hit still closes the terminal.
-
Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running.
This simply didn't work. For one thing, the registry keys it mentions don't exist on my system, and even after creating them from scratch and rebooting my system, ctrl-c still kills the terminal.