I have a function that I know will throw an error. This error is expected, but when it's thrown I want to end the function. I have a Trap section in my script, and I have used both the Return
and the Break
commands, but they don't do what I want. I have the trap statement both in the Begin {}
and the Process {}
sections. I am using the command Get-WmiObject
, and I have the -ErrorAction
set to stop
. A sample of the code and their responses are below.
First Example w/ return:
Function Test {
Param {"Some Parameters"}
Begin {"Some beginning stuff"}
process {
Trap
{
Add-Content $($SomeFile) $($ComputerName + "is Not There")
return
} #End Trap
Get-WmiObject Win32_NTLogEvent `
-ComputerName $ComputerName `
-Credential $Cred - `
-ErrorAction Stop
}#End Process
End {"Some ending things"}
} #End Function
This one simply keeps going on, without exiting the function.
Second Example w/ break:
Function Test {
Param {"Some Parameters"}
Begin {"Some beginning stuff"}
process {
Trap
{
Add-Content $($SomeFile) $($ComputerName + "is Not There")
Break
} #End Trap
Get-WmiObject Win32_NTLogEvent `
-ComputerName $ComputerName `
-Credential $Cred - `
-ErrorAction Stop
}#End Process
End {"Some ending things"}
} #End Function
This one exits the entire script.
I have looked around, but I can't find anything specific to exiting just a function. There is a lot more going on in the function, including another Get-WmiObject
command. I want it to exit the function if the first Get-WmiObject
can't contact the computer. I can't use a ping test, because many of the servers block ICMP.
The
$?
varible can be good for catching errors. It contains a boolean for the last executed command. If the command was excuted without errors$? = $true
. The$?
will be$false
when the last executed command errored.Create a boolean that gets set each time after the command that errors. Assuming that the command here is get-wmiObject:
Since you probably have a conditional in your loop already, it would look something like
while(<condition> -and $running)
And if you would like to add your error message in, just throw something after you set running like this
Return will in fact not help, but you can use break, the only requirement is to use it as it was designed - to get out of the loop... :)
Trick here is to build simple loop that will run only once no matter what and use break inside the loop:
The reason behind it is the fact, that break is loop directive and in PowerShell it does not care for any limits (so break in script, run from script, run from script will be able to walk all the way up and kill whole thing, unless it find some loop to stop him).
I blogged about this issue a while ago.
Try "Continue" as keyword
Trap [Exception] { “In PowerShell” }