Exit - PowerShell


Overview

The Exit command in PowerShell immediately terminates the current PowerShell session, including any currently running scripts or commands. It is primarily used for abruptly ending a session or controlling program flow in scripts.

Syntax

Exit [[-Code] <int>] [-Force]

Options/Flags

  • -Code: Specifies an exit code to return to the calling process. The default is 0 for successful execution.
  • -Force: Terminates all PowerShell sessions without prompting for confirmation. This flag is typically used in scripts to ensure a clean exit.

Examples

Simple usage:

PS> Exit

This immediately exits the current PowerShell session.

Exit with a code:

PS> Exit -Code 1

This exits the session with an exit code of 1, indicating an error.

Forceful exit from a script:

If ($Error.Count -gt 0) {
    Exit -Force
}

This script ensures that the session exits if any errors occur, without prompting for confirmation.

Common Issues

  • Unexpected exit: If the -Force flag is not used, the command will prompt for confirmation before exiting. To avoid this, use the -Force flag in scripts.
  • Error handling: Always handle errors properly in scripts. Otherwise, the Exit command may terminate the script unexpectedly.

Integration

The Exit command can be integrated with other PowerShell commands using the pipeline. For example, you can chain the Exit command with ForEach-Object to exit a session after processing each object in a collection:

Get-Process | ForEach-Object {
    If ($_.Responding -eq $false) { Exit -Code 2 }
}
  • Break: Terminates the current execution block.
  • Continue: Skips the remaining statements in the current block and continues execution at the next block.