Powershell – How to exit a function in powershell

error handlingpowershell

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.

Best Answer

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:

$running = $true
While ($running) {
Get-WmiObject Win32_NTLogEvent -ComputerName $ComputerName -Credential $Cred
$running = $?
}

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

if(!$running){Add-Content $($SomeFile) $($ComputerName + "is Not There")  }