Why doesn’t `exit` close the PowerShell window running my script?

0
0
Asked By MellowCedar42 On

I'm running this as a `.ps1` file. The script searches for `.pubxml` publish profiles, finds the related project files, and runs `dotnet publish` for each one. I added `exit 1` as the final line, expecting the active PowerShell window to close, but the window stays open. Does `exit` only stop the script, and what should I use if I really need to terminate the hosting process?

3 Answers

Answered By QuietMaple18 On

`[System.Environment]::Exit(0)` forcibly terminates the entire PowerShell host, not just the script. That can close the window, but it’s usually not recommended, especially when the script is running inside an editor or another hosted PowerShell environment. Prefer `exit 0` or another appropriate code when you only need to end the script.

Answered By BriskLantern7 On

In a normal PowerShell script, `exit` ends the script and returns an exit code to whatever launched it. It doesn’t necessarily close an already-open PowerShell or integrated terminal window. If you started PowerShell specifically to run the script, that separate process may close when the script ends; an existing terminal session generally remains open.

MellowCedar42 -

That clears it up—I was assuming `exit` would always close the shell window too. I only need it to end the script and provide a status code.

Answered By CopperOrbit53 On

There also appears to be a formatting or copy-paste problem near the end: `exit 1$profiles = Get-ChildItem ...` would combine two statements into one invalid line. Make sure the script ends cleanly and that the `exit` statement is on its own line. Also, use `exit 0` for success; `exit 1` conventionally indicates failure.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.