This tutorial will observe several approaches to terminate a PowerShell script.
How to Terminate a Script in PowerShell?
These are the approaches that can be utilized to terminate a script in PowerShell:
Method 1: Terminating a Script in PowerShell Using “Exit” Command
The “Exit” cmdlet is used to take an exit from a PowerShell wherever it is executed. It is majorly utilized inside the functions. As a result, it only terminates the script but not the console. Similarly, executing it outside the script will terminate the console.
Example
For instance, the given script will get terminated after executing the first “write-host” command:
write-host "Exit command will terminate the script"
exit
Write-host "This will not execute"
}
Test
As you can see, the code after the “Exit” keyword did not execute and the script got terminated.
Method 2: Terminating a Script in PowerShell Using “Break” Command
The “Break” cmdlet is a different one from the rest of the terminating commands. It is normally used in switch statements and loops to terminate a PowerShell script. For instance, if there are 5 lines to be executed and the Break statement is used after the third line. Then, the script will get terminated after the execution of the third line and the other two lines won’t execute.
Note that this command will only terminate a PowerShell script but not a PowerShell console.
Example
In this example, the added “Break” command will break the execution control of the “Test” function:
write-host "Break command will terminate the script"
Break
Write-host "This will not execute"
}
Test
Method 3: Terminating a Script in PowerShell Using “Return” Command
The “Return” keyword or command does not directly terminate a script, but it returns the code to the point where it was called previously. If this command is executed in the console, it will not return anything. However, executing it inside the script will terminate it.
Example
Here is the demonstration of the termination of the PowerShell script using the “Return” command:
write-host "Return command will terminate the script"
return
Write-host "This will not execute"
}
Test
The output confirms that the script got terminated, after the execution of the “Return” command.
Conclusion
The script in PowerShell can be terminated using various commands. These commands include the “Exit”, “Break”, or “Return”. All these commands need to be executed inside a PowerShell script to terminate it. This post has demonstrated several methods to terminate a script in PowerShell.