Error Handling In Powershell 2.0
being able to handle errors helps to ensure that an unexpected event will not go on to wreck the system you are working on. Take the example below. Every week in our sample company (MyCompany.Com) Human Resources are going to upload a list telling us who should have access to the Expenses database. If a name isn’t in the list from HR we’re going to remove it from the group and that user will no longer be able to log expense claims: $AuthorizedUsers= Get-Content \\ FileServer\HRShare\UserList.txt $CurrentUsers=Get-ADGroupMember "Expenses Claimants" Foreach($User in $CurrentUsers) { If($AuthorizedUsers -notcontains $User) { Remove-ADGroupMember -Identity "Expenses Claimants" -User $User } } Now, you can see where this is going to go wrong. One week HR doesn’t get around to uploading the list or, just as we are about to access the list, the file server dies. Suddenly PowerShell throws an error on the Get-Content cmdlet and the $AuthorizedUser variable remains empty. Because our script doesn’t handle errors, it continues to run and, in a very short space of time, it has removed every user from our expenses group. Pretty soon the irate phone calls start flooding in and life gets a little less happy. The way to avoid all this is to catch the errors and then handle the event that caused them (which in this case is halt the script and have a shout at someone in HR). Terminating and Non-Terminating Errors One of the key things to know when catching errors is that only certain errors can be caught by default. Errors come in two types – terminating and non-terminating. A terminating error is an error that will halt a function or operation. If you make a syntax error or run out of memory, that is a terminating error. Terminating errors can be caught and handled. Non-terminating errors allow Powershell to continue and usually come from cmdlets or other managed situations. Under normal circumstances they cannot be caught by Try-Catch-Finally. The Get-Content error in the example above is a non-terminating error. Treating Non-Terminating Errors as Terminating So how do you catch a Non-Terminating error? Basically, you tell PowerShell to treat it as terminating. To do this you use the ErrorAction parameter. Every PowerShell cmdlet supports ErrorAction. By specifying -ErrorAction Stop on the end of a cmdlet you ensure that any errors it throws a
Platforms Ask the Core Team Cloud Platform Blogs Hybrid Cloud Microsoft Azure Building Clouds Datacenter Management Hybrid Cloud Operations Management Suite (OMS) System Center Virtual Machine Manager System Center Service Manager System Center Operations Manager System Center Orchestrator System Center Data Protection Manager Client Management System Center Configuration Manager Configuration Manager Team System Center Service Manager Malware Protection Center Microsoft Intune Server Update Services Enterprise Mobility Virtualization, VDI & Remote Desktop Virtualization Team Ben Armstrong's Virtualization Remote Desktop Services Ask the Core Team on Hyper-V Enterprise Mobility File & Storage & High Availability File & Storage Ask the Core Team on Failover Cluster http://www.vexasoft.com/blogs/powershell/7255220-powershell-tutorial-try-catch-finally-and-error-handling-in-powershell Clustering & High Availability Windows Server Management PowerShell Hey Scripting Guy (PowerShell) Networking Identity, Access & Security Datacenter and Private Cloud Security Active Directory Enterprise Mobility Ask Directory Services Hey, Scripting Guy! Blog Learn about Windows PowerShell Weekend Scripter: Using Try, Catch, Finally Blocks for PowerShell Error Handling ★★★★★★★★★★★★★★★ July 5, 2014July 4, 2015 by The Scripting Guys // 4 Comments 0 0 0 Summary: Microsoft PFE, Ashley McGlone, talks about https://blogs.technet.microsoft.com/heyscriptingguy/2014/07/05/weekend-scripter-using-try-catch-finally-blocks-for-powershell-error-handling/ using Try, Catch, Finally blocks for error handling in Windows PowerShell. Microsoft Scripting Guy, Ed Wilson, is here. Today’s guest blogger is Ashley McGlone, a Microsoft premier field engineer. Ashley is a popular speaker at our Windows PowerShell Saturday events. He regularly blogs about Active Directory and Windows PowerShell at Goatee PFE. You can follow him on Twitter as @GoateePFE. Take it away, Ashley… Why do scripts have errors? That is a long philosophical debate, and there is more than one correct answer. The generally accepted answer is that they are written by humans, and humans are not perfect. Even when considering all of the reasons there are errors in scripts, the root cause is usually a difference in expectations. I expect the code or data to be X, but really it is Y. And that is why we need error handling. There are many ways to handle errors in Windows PowerShell, including: $Error.Clear(); Do-Something; If ($Error) {..} Else {..} Trap $ErrorActionPreference Try, Catch, Finally is similar to a Trap block. Trap blocks generally catch any errors in the scope of the entire script or function. The beauty of Try, Catch, Finally is that it is like a localized Trap for a specific block of commands. This gives you great flexibility
handling gotcha in PowerShell 2.0 Posted on October 23, 2011 by Jan Egil http://blog.powershell.no/2011/10/23/test-connection-error-handling-gotcha-in-powershell-2-0/ Ring The Test-Connection cmdlet in Windows PowerShell was introduced in version 2.0, with the purpose of sending ICMP echo request packets https://posh2scripting.wordpress.com/error-handling-and-trap/ ("pings") to one or more computers as stated in the cmdlets documentation.
The cmdlet has a number of useful parameters, error handling for example –Count to specify the number of request packets to send (the default is 4) and –Quiet to suppress errors and make the cmdlet return either true or false:
The –Quiet parameter error handling in is very useful when writing a script or function where you only want to perform an operation if the target computer responds to ping requests. A basic example of using this technique: