EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Exit
Secondary Sidebar
PowerShell Tutorial
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Interview Questions
    • PowerShell Interview Questions

Related Courses

Shell Scripting Course

All in One Data Science Courses

Data Visualization Courses

PowerShell Exit

PowerShell Exit

Definition of PowerShell Exit

PowerShell exit functions or cmdlets are the scripts or the function terminators. Using Exit functions in PowerShell doesn’t always terminate the console, it depends on the command and the scope in the script used as the same command can terminate the console and the same command can terminate the function or the script is used in the different scope and Exit cmdlet is also useful for exiting the remote PowerShell session.

All in One Data Science Bundle(360+ Courses, 50+ projects)
Python TutorialMachine LearningAWSArtificial Intelligence
TableauR ProgrammingPowerBIDeep Learning
Price
View Courses
360+ Online Courses | 50+ projects | 1500+ Hours | Verifiable Certificates | Lifetime Access
4.7 (86,112 ratings)

Syntax

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

Few cmdlets are used as an Exit function for the PowerShell and they are as below.

  • Exit
  • Break
  • Return <Expression>
  • Exit-PSSession

How does Exit Function work in PowerShell?

Working of exit functions in PowerShell are given below:

1. Exit Keyword

PowerShell Exit Keyword should be used carefully because it can terminate function, console, or even the editors. If the Exit keyword is used in the functions and the main script, it closes everything and you may not get a chance to see the output in the console if not stored before the Exit Keyword is used.

Function ExitTest{
Write-Output "This is written on console but it terminates abruptly"
}
ExitTest  #Calling function
Exit

You can’t see the above output because as soon as you run the command it terminates the script. You can use the Sleep command with more seconds (10 or more) or pause to see the output for few seconds.

When the Exit keyword is used inside a function and saved in the script, and once the script is executed from the console, it terminates the function and the script but won’t close the console as shown in the below example.

Function ExitTest{
Write-Output "This will be displayed"
Exit
}
ExitTest  #Calling function

Write-Output “This Won’t be displayed but console will not closed”

Output:

PowerShell Exit-1.1

2. Break Keyword

The break keyword is used in the loops (For, foreach, while, do-while, etc..) to exit from the current control loop. This Break statement is also used with the Switch statement as well.

When the break statement is used for the single loop, it exits the entire loop when the Break statement is executed.

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

In the above example, when the value of the variable $i becomes 5, it executes the Break statement, and the loop main For loop is terminated. The output is as shown below.

Output:

PowerShell Exit-1.2

Let’s take the nested loop example. In the below example, when the value of the $i variable becomes 2, the break statement is executed.

for($i=1;$i -lt 5;$i++){
for($j=1; $j -lt 3; $j++){
if($i -eq 2){break}
Write-Output "`ni = $i, j=$j"
}
}

Output:

PowerShell Exit-1.3

In the above example, when the inner loop is executed ($j loop) and when it has a break statement, it breaks only that current control loop as shown in the output, when the $i variable value becomes 2, it breaks the $j loop.

If we put the break statement outside, it breaks both the loops as shown below.

for($i=1; $i -lt 5 ;$i++) {
if($i -eq 2) { break }
for($j=1; $j -lt 3; $j++){
Write-Output "`ni = $i, j=$j"
}
}

Output:

PowerShell Exit-1.4

3. Return Keyword

The return statement doesn’t terminate the loop or the script but it redirects and returns to the point where it was called. When the return statement is called from the console it doesn’t return to another point but simply prints the value.

return "Hello world"

Output:

PowerShell Exit-1.3..

And when it is called from the Script, it saves the state of the original point from where it was called and returns to that point again.

function CheckService($ser) {
if( Get-Service $ser -EA Ignore){ return $true}
else {return $false }
}
If( CheckService TestService ) {
Write-Output "Service Exist"
}
else { Write-Output "Service doesn't exist" }

Output:

PowerShell Exit-1.5

In the above example, the function name called CheckService returns true if the service is available else it returns false.

Examples of PowerShell Exit

Following are the examples are given below:

Example #1

Using Exit Console with Sleep Command

In this example, we will use the Exit command with the Sleep function so that the script terminates after few specified seconds.

Code:

$i = 0
While($true){
$i
if($i -eq 10){
Write-Output "Console is terminating in 3 seconds"
sleep 3
Exit
}
$i++
}

Here, in the infinite loop, if the value of the $i variable reaches 10, it automatically closes the console after 3 seconds.

Example #2

Using Break statement to exit from the While Loop.

This example checks if the server LabMachine2k16 is online after reboot or not and it continuously tests connection until the server comes up and once the server is up it uses the break command to exit from the loop.

Code:

$Computer = "LabMachine2k16"
while($true){
if( Test-Connection -ComputerName $Computer -Count 2 -Quiet -EA Ignore  ){
Write-Output "Server is online"
Break
}
else{
Write-Output "Server is not online yet"
}
}

Output:

Output-1.6

Example #3

Using Break Statement to Exit from The Switch Block

We can use the Break command with the Switch block as well. For example,

Code:

$color = Read-Host "Enter Color name "
switch($color){
"Red"{
Write-Output "Red color selected"
Break
}
"Yellow"{
Write-Output "Yellow color selected"
Break
}
Default{
Write-Output "No matching color selected"
Break
}
}

Output:

Output-1.7

Once the color name is entered, the switch block is executed and terminated with the Break statement.

Example #4

Using Return statement to return value to the call.

In this example, two values are multiplied in the function, and the output is returned to the main call.

Code:

Function Multiplication($a,$b){
return $a*$b
}
$out = Multiplication 5 10
Write-Output "Multiplication: $out"

Output:

Output-1.8

Example #5

Using Exit-Ps Session Command to Exit the Remote Session

Exit-PSSession is used to terminate the remote connected session. However, this can’t be used inside the PowerShell script, it is an interactive method. Below commands are executed one by one on the PS console.

Code:

Enter-PSSession LabMachine2k16  #Enters into PS Remote Session
Write-Output "My HostName is $($env:COMPUTERNAME)"
Exit-PSSession

Output:

Output-1.9

Conclusion

There are various Exit commands available to exit the console, terminate the loop, or return to the original point of the console and which statement to use is depends on the way you want the script to generate output or script to be terminated.

Recommended Articles

This is a guide to PowerShell Exit. Here we also discuss the definition and How do Exit Functions Work in PowerShell? along with different examples and its code implementation. You may also have a look at the following articles to learn more –

  1. Start PowerShell from cmd
  2. PowerShell Match
  3. PowerShell JSON Format
  4. Powershell Copy File
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

SPSS, Data visualization with Python, Matplotlib Library, Seaborn Package

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more