Try & Catching Errors so you can relax Finally.

Sometimes you gotta Try…. okay enough pep talk.

using the Try Command will allow you to catch any terminating errors. unless you specify for some commands you will not catch the errors and may not want to actually.

example:

 Try{ get-childitem c:\incorrectlyspelledfolder\  -erroraction Stop -recurse -errorvariable ErrorCity}

#for every Try there must be a catch

Catch {write-host "Error: $($errorCity.gettype().fullname)"}

I wrote this to have the error show the  expression needed to catch specific errors you actually care about.

so you can to catches or specific instructions to go with specific errors. lie write this to one file and email the results on another catch instance.

Example:

  Try{ 
$folder="c:\windows"
get-childitem $folder -erroraction Stop -recurse -errorvariable ErrorCity -OutVariable Results 
}
 #for every Try there must be a catch #specific to error records now it will write the line.
catch [System.Management.Automation.ErrorRecord]{Write-host "Typo?"} #this catch will catch any other error like permission denied, etc. 
Catch {write-host "Error: $($errorCity.gettype().fullname)" -ForegroundColor Red} 


Finally{write-host "finished processing $folder " -ForegroundColor Green
        write-host "Sub Folders are :"
        $Results.fullname
        }
#finally is optional to do a set of command regardless of error on the object being processed.
Good Luck Trying & catching errors and finally understanding.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s