I have a small script I’m working on to check for locked AD accounts, and then optionally unlock them. One of the first checks is to see how many accounts are currently locked. If there are zero locked accounts I want the script to terminate. I’ve seen a few posts arguing the merits of Exit/Return/Break, and I’m wondering what the best way to go would be. Thoughts? Suggestions?
If ($NumberOfAccounts -eq 0)
{
Write-Host ("There are currently no accounts locked") -ForegroundColor Green
# Exit code??
}
exit $code is the most recognisable and typically useful way to report an actual exit code. You can do similar things with the methods buried a couple levels deep in the $host automatic variable, but it’s easiest to use the keyword.
I’m just looking for a way to exit from the script, not the console. I thought about wrapping it in a huge if…else statement, but that seemed inefficient.
cls
1..9 | %{
If ($_ -ne 7){"Not 7 yet, so no break $_"}
Else {
Write-Warning -Message "Hello, I hit $_ breaking..."
break
Write-Host 'New line after break ' -ForegroundColor Cyan
Get-Date
}
}
But it depends on which context you’re in.
Break and return will produce the same result if you’re in the same scope.
E.g. lets say you have a script and not using functions in the script both return and break will stop executing the script.
If you are executing some code in a function in that script.
Return will exit the function but will continue with the script.
Break will stop execution of the rest of the script.
Exit will exit the script and close the console.
In regard to Exit it depends on what you want to achieve afterwards.
Exit 0 will return the exit/errorcode of 0.
Exit ‘any none zero’ value will produce the exit/errorcode of 1.
So if you want more granular error codes than 0 or 1.
Use: [System.Environment]::Exit(any_number) or $host.SetShouldExit(any_number).
Haven’t explored ways to capture the error code other than running the script from a normal command prompt.
Since the console will exit once it hits one of the exit variants.
But I’m sure you can do it somehow, maybe launching the script in a new powershell session might work.
Haven’t tested it though.