End an interactive PowerShell session (with a local or remote computer).

      Exit-PSSession [CommonParameters] ErrorLevel

       -Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
       -OutBuffer -OutVariable.

Standard Aliases for Exit-PSSession: exsn and exit

This cmdlet should not be confused with the exit statement in other languages which can exit a function and return to the caller. Exit-PSSession will always terminate the current script, or at an interactive PowerShell prompt, will abort the entire PowerShell session. To simply stop script execution use break.

Exit Codes

In PowerShell $? contains True if last operation succeeded and False otherwise.

The exit code of the last Win32 executable execution is stored in the automatic variable $LASTEXITCODE

To read exit codes (other than 0 or 1) launch the PowerShell script and return the $LASTEXITCODE in a single line like this:

powershell.exe -noprofile C:\scripts\script.ps1; exit $LASTEXITCODE


Start and then stop an interactive session with the Server64 remote computer:

PS C:> Enter-PSSession -computername Server64
Server01\PS> Exit-PSSession

Start and stop an interactive session with Server64, the status of the PSSession shows that the session is still available when the interactive session ends.:

PS C:> $sess = new-pssession -computername Server64
C:\PS> Enter-PSSession -session $sess
Server01\PS> Exit-PSSession
C:\PS> $sess

Id Name ComputerName State ConfigurationName
-- ---- ------------ ----- -----------------
1 Session1 Server64 Opened Microsoft.PowerShell

Note that if Enter-PSSession -ComputerName is used (instead of new-psSession), then Enter-PSSession would have automatically created a temporary session that would close as soon as the interactive session ends.

Start PowerShell.exe and run a cmdlet and exit returning an ErrorLevel back to the calling shell (in this case CMD.exe)

C:\> powershell.exe -noprofile -command get-process; Exit-PSSession 64

“Every exit is an entrance somewhere else” ~ Tom Stoppard


Enter-PSSession - Start an interactive session with a remote computer
Remove-PSSession - Close PowerShell sessions (non-interactive)
Break - Exit a program loop
Continue - Skip just this iteration of a loop
Return - Exit the current scope, (function, script, or script block).

Copyright © SS64.com 1999-2017
Some rights reserved