Exit-PSSession

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

Syntax
      Exit-PSSession [CommonParameters] ErrorLevel

Key

   ErrorLevel   An exit code to return between 0 and 65535.
                An exit code of 0 indicates success.

Standard Aliases for Exit-PSSession: exsn

This cmdlet should not be confused with the exit statement or keyword 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 exit the entire PowerShell session.
To 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

Examples

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
PS C:\> Enter-PSSession -session $sess
Server01\PS> Exit-PSSession
PS C:\> $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
C:\> Echo %ERRORLEVEL%
64

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

Related PowerShell Cmdlets

Enter-PSSession - Start an interactive session with a remote computer.
Disconnect-PSSession - Disconnect from a session.
Remove-PSSession - Close PowerShell sessions (non-interactive).
Exit - Keyword, Exit a script or exit PowerShell.


 
Copyright © 1999-2024 SS64.com
Some rights reserved