How to Use the PowerShell Exit Command and Friends

Published:28 September 2021 - 4 min. read

Bill Kindle Image

Bill Kindle

Read more tutorials by Bill Kindle!

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Have you ever wondered, “What is the best way to terminate a script or exit a command in PowerShell?” Will the PowerShell session close with the PowerShell exit command? How to return custom exit codes? Well, you are in luck!

In this guide, you’ll have these questions and more answered. Learn about all the ways to exit a PowerShell script or session.

Let’s get ready to terminate some PowerShell sessions and scripts!

Announcing a Free LIVE training – Starting your PowerShell Journey – presented by Johan Arwidmark. Understand how PowerShell skills enhance your IT career, learn where to start with PowerShell, build your first scripts, and ask Johan questions directly in a live training environment.

Prerequisites

To follow along, be sure to have Windows PowerShell or PowerShell Core installed on your machine. The examples in this article will use PowerShell 7.1.4.

Terminating the Console and Scripts with PowerShell Exit Command

Let’s dig into this tutorial and first cover the exit keyword, one of the many reserved words in PowerShell. A reserved word is a set of characters built into PowerShell that performs some action. For the exit keyword, the action is making PowerShell exit a PowerShell session.

Let’s practice! Open a PowerShell console session, type exit, and press the Enter key. The PowerShell console will immediately close.

This keyword can also exit a script rather than the console session. Including the exit keyword in a script and exit terminates only the script and not the entire console session from where the script runs.

Copy and paste the code below into notepad and save the script as test.ps1 to the C:\Temp directory. Run the PowerShell script file by running the command .\text.ps1 as shown in the below screenshot. Notice that instead of PowerShell closing the session, PowerShell terminates the script and returns control to the prompt of the current PowerShell session.

# test.ps1
Write-Host "Quick! Read this before the PowerShell session closes!!"
Start-Sleep -Seconds 2
Exit
The exit keyword stopped the script execution, but the console is still running
The exit keyword stopped the script execution, but the console is still running

Receiving and Providing Feedback with Exit Codes

The exit command is helpful for situations when you need a script or function to run some code and exit. But you are not getting any indication if the script ran successfully or not.

When PowerShell runs the last command in a script, it stores the exit code of that last command in the $LASTEXITCODE variable.

There are two default exit codes:

PowerShell does not restrict you to 0 and 1 as exit codes. PowerShell lets you return custom exit codes, as long as they are integers.

The range of values for the exit code is platform-dependent. On Windows, any 32-bit signed integers are allowed. On Unix, only positive 8-bit integers are allowed.

To exit PowerShell with a custom exit code, you can provide the exit code as an argument for the exit keyword.

Copy and paste the code below in the existing test.ps1 file and run the script with the command .\Test.ps1. Check the content of the $LASTEXITCODE variable. By telling PowerShell to exit with a 55 exit code, it did so, as you can see below.

Function foo {
    Write-Output "This foo function will be shown"
    Exit 55 # < -- Using custom exit code
}

foo
Returning a custom exit code
Returning a custom exit code

Breaking Out of Loops With Break

There will be moments where the exit behavior is not acceptable: like quitting a function. Let’s check how the break keyword helps.

The break keyword makes PowerShell stop a loop. After a break, the code continues executing at the next iteration.

Breaks are helpful in PowerShell loops such as the foreach, while, do-while, and switch statements because you can control where your code will halt before your code completes.

Let’s practice breaking out of loops. Below you can see a snippet code with a for loop. The for loop would iterate ten times if not for the break within. The break keyword will be triggered when the iterator is equal to eight. Once PowerShell finds the break keyword, it stops the loop.

for($i=1; $i -le 10; $i++) {
	if($i -eq 8) { break }
	$i
}

You can see below that PowerShell stops the loop when i equals 8. The code never goes to 9. You have successfully broken out of a for loop.

Breaking a for loop
Breaking a for loop

Redirecting Code Execution with Return

The return keyword is slightly different from the previous keywords as it doesn’t exit or break commands. This keyword redirects code execution. It returns execution to its call while allowing you to return values. And not just integers, like exit, mind you. You can return any type! These behaviors make the return keyword more versatile than the previous keywords.

Let’s see it in action with an example: building a function to pair words. Copy the code below into your PowerShell session:

function WordPairing ($a,$b) {

	return "$a" + "$b" # <-- Combining two words into one word

}

$output = WordPairing taco cat

Write-Output "$output is a strange pairing of words."

Notice how the value you are returning from the function in the output.

Redirecting code execution with the return keyword
Redirecting code execution with the return keyword

You redirect the $output generated by the WordPairing function back to where the $output is called.

Announcing a Free LIVE training – Starting your PowerShell Journey – presented by Johan Arwidmark. Understand how PowerShell skills enhance your IT career, learn where to start with PowerShell, build your first scripts, and ask Johan questions directly in a live training environment.

Conclusion

In this guide, you’ve learned different ways to terminate PowerShell sessions and scripts. Each method relies on a specific keyword. Each keyword has a particular use case. When used appropriately, each of these keywords gives you enormous control over what your script does.

Now that you know different ways for exiting your PowerShell sessions, how do you plan to improve your scripts with this newfound knowledge?

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!