try catch finally powershell code example

Example 1: invokemethodonnull powershell try catch

PS C:\Scripts\PowerShell> C:\Scripts\PowerShell\Add SA3Cloud\Add-SA3Cloud.ps1
Office is: \\sa3cloud\LOPD
Location is LOPD
WARNING: \\sa3cloud\LOPD
WARNING: System.Management.Automation.RuntimeException: You cannot call a method on a null-valued expression.
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

Example 2: powershell try catch connect-viserver

try {
    Write-debug "Connecting to vCenter, please wait.."
    #Connect to vCenter
    Connect-ViServer -server $vcInfo.server -credential $creds -ErrorAction Stop | Out-Null
  }
  catch [Exception]{
    $status = 1
    $exception = $_.Exception
    Write-debug "Could not connect to vCenter"
    $msg = "Could not connect to vCenter"
    LogSysTo-File $msg $status $env:username $exception.message
  }