Exit-PSSession

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

Syntax
      Exit-PSSession [CommonParameters] ErrorLevel

Key
   CommonParameters:
       -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.

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
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 .ps1 script that will exit returning an ErrorLevel back to the calling shell (in this case CMD.exe)

C:\> powershell.exe -noprofile –file "C:\bats\DemoScript.ps1"
:: DemoScript.ps1ends with the line: Exit-PSSession 64
C:\> Echo %ERRORLEVEL%
64

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

Related:

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-2015
Some rights reserved