{"id":418,"date":"2019-03-26T08:00:58","date_gmt":"2019-03-26T14:00:58","guid":{"rendered":"https:\/\/practicalpowershell.com\/?p=418"},"modified":"2020-03-13T16:28:14","modified_gmt":"2020-03-13T22:28:14","slug":"try-and-catch-being-practical","status":"publish","type":"post","link":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/","title":{"rendered":"Try and Catch &#8211; Being Practical"},"content":{"rendered":"<p><a href=\"https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?ssl=1\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" src=\"https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?resize=150%2C150&#038;ssl=1\" alt=\"\" width=\"150\" height=\"150\" class=\"alignleft size-thumbnail wp-image-419\" srcset=\"https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?resize=150%2C150&amp;ssl=1 150w, https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?resize=100%2C100&amp;ssl=1 100w, https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?zoom=2&amp;resize=150%2C150&amp;ssl=1 300w\" sizes=\"auto, (max-width: 150px) 100vw, 150px\" \/><\/a>Practically speaking, Try and Catch pairs can perform many functions. They can simply be there for error handling, can be used to determine the next set of actions or even to execute and optional set of commands. In fact, we can use the pair to log different cmdlet outcomes if something fails or is not available to a particular PowerShell session. Let&#8217;s explore some of the ways we can use Try {} Catch {} in a practical manner.<BR><br \/>\n<em>Decision Making<\/em><BR><br \/>\nThis is an overly broad definition as it can cover many scenarios as well. However it is a very useful trick in PowerShell. Here are some examples:<BR><br \/>\n<em>Determine if a Module Loaded Properly<\/em><BR><br \/>\nSome scripts may require cmdlets from multiple PowerShell modules, like Exchange and Active Directory for an example. On an Exchange Server we can determine if the AD PowerShell module was properly loaded like so:<br \/>\n[sourcecode language=&#8221;powershell&#8221;]<br \/>\n$ADModuleLoaded = $True<br \/>\nTry {<br \/>\n    Import-Module ActiveDirectory -ErrorAction STOP<br \/>\n} Catch {<br \/>\n    $ADModuleLoaded = $False<br \/>\n}<br \/>\n[\/sourcecode]<br \/>\nIn the above code, we set the $ADModuleLoaded variable to $True. If the module fails to load, then the same variable will be changed to $False. Later in the script we can then perform different actions based on the $ADModuleLoaded variable&#8217;s value. So, say the variable is true and thus the module loaded properly, we can run a series of AD related cmdlets. However if the $ADModuleLoaded variable is $False, then we could skip these cmdlets and record the problem in some sort of log file.<BR><br \/>\n<em>Determine To Proceed Further<\/em><BR><br \/>\nLet&#8217;s say for an example we are checking an Exchange Server for the existence of Public Folders. If none exist, we skip trying to getting detailed stats on them. Whereas if we find the folders, we can instead check Public Folder statistics.<br \/>\n[sourcecode language=&#8221;powershell&#8221;]<br \/>\n$PFCheck = 0<br \/>\nTry {<br \/>\n    $PFCheck = (Get-PublicFolder &quot;\\&quot; -Recurse -ErrorAction STOP).Count<br \/>\n} Catch {<br \/>\n    $Line = &quot;No Public Folders can be found!&quot; | Out-file $Destination -Append<br \/>\n}<br \/>\nIf ($PFCheck -ne 0) {<br \/>\n    Get-PublicFolder &quot;\\&quot; -Recurse | Get-PublicFolderStatistics<br \/>\n}<br \/>\n[\/sourcecode]<br \/>\nAbove we can use PowerShell Try {} Catch to determine if there are Public Folders and thus the ability or possibility to check for Public Folders. <BR><br \/>\n<em>Catch Failures<\/em><BR><br \/>\nTry and Catch is generally designed for this. We can use the cmdlet pair as a way to simply catch errors that may be generated by a cmdlet without putting them on the screen. Once caught, they can be logged to a file possibly like so:<br \/>\n[sourcecode language=&#8221;powershell&#8221;]<br \/>\nTry {<br \/>\n    $Line = Get-DistributionGroup -ResultSize Unlimited | Where {$_.recipientTypeDetails -eq &#039;RoomList&#039;}<br \/>\n} Catch {<br \/>\n    $Line = &#039;Retrieving Room Lists Failed.&#039; | Out-File $Destination -Append<br \/>\n    $Line = &quot;$Date,Error message &#8211; $_.Exception.Message&quot; | Out-File $Destination -Append<br \/>\n}<br \/>\n[\/sourcecode]<br \/>\nIn the above code, we are looking for a special feature called Room Lists. If the cmdlet fails we log the fact that this failed as well as the error message generated ($_.Exception Message). Then when we review our scripts log file we can see what happened and possibly fix the issue.<BR><br \/>\n<em>Summary<\/em><BR><br \/>\nAs you can see, Try and Catch has some definite practical uses. The above list is certainly not comprehensive and more just illustrative of some uses of the cmdlet pair.<BR><br \/>\n<em>&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;&#8212;-<br \/>\n*** If you found this post useful, please comment or like the post.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Practically speaking, Try and Catch pairs can perform many functions. They can simply be there for error handling, can be used to determine the next set of actions or even to execute and optional set of commands. In fact, we can use the pair to log different cmdlet outcomes if something fails or is not [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rop_custom_images_group":[],"rop_custom_messages_group":[],"rop_publish_now":"initial","rop_publish_now_accounts":[],"rop_publish_now_history":[],"rop_publish_now_status":"pending","_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[1],"tags":[],"class_list":["post-418","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.3 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Try and Catch - Being Practical - Practical PowerShell<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Try and Catch - Being Practical - Practical PowerShell\" \/>\n<meta property=\"og:description\" content=\"Practically speaking, Try and Catch pairs can perform many functions. They can simply be there for error handling, can be used to determine the next set of actions or even to execute and optional set of commands. In fact, we can use the pair to log different cmdlet outcomes if something fails or is not [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/\" \/>\n<meta property=\"og:site_name\" content=\"Practical PowerShell\" \/>\n<meta property=\"article:published_time\" content=\"2019-03-26T14:00:58+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-03-13T22:28:14+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally-150x150.jpg\" \/>\n<meta name=\"author\" content=\"damian\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"damian\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/\"},\"author\":{\"name\":\"damian\",\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/#\\\/schema\\\/person\\\/4d0733c81966e744aabbb49f56d64deb\"},\"headline\":\"Try and Catch &#8211; Being Practical\",\"datePublished\":\"2019-03-26T14:00:58+00:00\",\"dateModified\":\"2020-03-13T22:28:14+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/\"},\"wordCount\":538,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/#\\\/schema\\\/person\\\/4d0733c81966e744aabbb49f56d64deb\"},\"image\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/practicalpowershell.com\\\/wp-content\\\/uploads\\\/2020\\\/03\\\/TryCatchFinally-150x150.jpg\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/\",\"url\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/\",\"name\":\"Try and Catch - Being Practical - Practical PowerShell\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/practicalpowershell.com\\\/wp-content\\\/uploads\\\/2020\\\/03\\\/TryCatchFinally-150x150.jpg\",\"datePublished\":\"2019-03-26T14:00:58+00:00\",\"dateModified\":\"2020-03-13T22:28:14+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#primaryimage\",\"url\":\"https:\\\/\\\/i0.wp.com\\\/practicalpowershell.com\\\/wp-content\\\/uploads\\\/2020\\\/03\\\/TryCatchFinally.jpg?fit=324%2C231&ssl=1\",\"contentUrl\":\"https:\\\/\\\/i0.wp.com\\\/practicalpowershell.com\\\/wp-content\\\/uploads\\\/2020\\\/03\\\/TryCatchFinally.jpg?fit=324%2C231&ssl=1\",\"width\":324,\"height\":231},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/try-and-catch-being-practical\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/practicalpowershell.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Try and Catch &#8211; Being Practical\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/#website\",\"url\":\"https:\\\/\\\/practicalpowershell.com\\\/\",\"name\":\"Practical PowerShell\",\"description\":\"PowerShell books written by experts\",\"publisher\":{\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/#\\\/schema\\\/person\\\/4d0733c81966e744aabbb49f56d64deb\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/practicalpowershell.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/practicalpowershell.com\\\/#\\\/schema\\\/person\\\/4d0733c81966e744aabbb49f56d64deb\",\"name\":\"damian\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g\",\"caption\":\"damian\"},\"logo\":{\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Try and Catch - Being Practical - Practical PowerShell","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/","og_locale":"en_US","og_type":"article","og_title":"Try and Catch - Being Practical - Practical PowerShell","og_description":"Practically speaking, Try and Catch pairs can perform many functions. They can simply be there for error handling, can be used to determine the next set of actions or even to execute and optional set of commands. In fact, we can use the pair to log different cmdlet outcomes if something fails or is not [&hellip;]","og_url":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/","og_site_name":"Practical PowerShell","article_published_time":"2019-03-26T14:00:58+00:00","article_modified_time":"2020-03-13T22:28:14+00:00","og_image":[{"url":"https:\/\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally-150x150.jpg","type":"","width":"","height":""}],"author":"damian","twitter_card":"summary_large_image","twitter_misc":{"Written by":"damian","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#article","isPartOf":{"@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/"},"author":{"name":"damian","@id":"https:\/\/practicalpowershell.com\/#\/schema\/person\/4d0733c81966e744aabbb49f56d64deb"},"headline":"Try and Catch &#8211; Being Practical","datePublished":"2019-03-26T14:00:58+00:00","dateModified":"2020-03-13T22:28:14+00:00","mainEntityOfPage":{"@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/"},"wordCount":538,"commentCount":0,"publisher":{"@id":"https:\/\/practicalpowershell.com\/#\/schema\/person\/4d0733c81966e744aabbb49f56d64deb"},"image":{"@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#primaryimage"},"thumbnailUrl":"https:\/\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally-150x150.jpg","inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/","url":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/","name":"Try and Catch - Being Practical - Practical PowerShell","isPartOf":{"@id":"https:\/\/practicalpowershell.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#primaryimage"},"image":{"@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#primaryimage"},"thumbnailUrl":"https:\/\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally-150x150.jpg","datePublished":"2019-03-26T14:00:58+00:00","dateModified":"2020-03-13T22:28:14+00:00","breadcrumb":{"@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#primaryimage","url":"https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?fit=324%2C231&ssl=1","contentUrl":"https:\/\/i0.wp.com\/practicalpowershell.com\/wp-content\/uploads\/2020\/03\/TryCatchFinally.jpg?fit=324%2C231&ssl=1","width":324,"height":231},{"@type":"BreadcrumbList","@id":"https:\/\/practicalpowershell.com\/try-and-catch-being-practical\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/practicalpowershell.com\/"},{"@type":"ListItem","position":2,"name":"Try and Catch &#8211; Being Practical"}]},{"@type":"WebSite","@id":"https:\/\/practicalpowershell.com\/#website","url":"https:\/\/practicalpowershell.com\/","name":"Practical PowerShell","description":"PowerShell books written by experts","publisher":{"@id":"https:\/\/practicalpowershell.com\/#\/schema\/person\/4d0733c81966e744aabbb49f56d64deb"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/practicalpowershell.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/practicalpowershell.com\/#\/schema\/person\/4d0733c81966e744aabbb49f56d64deb","name":"damian","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g","caption":"damian"},"logo":{"@id":"https:\/\/secure.gravatar.com\/avatar\/d5a8cc64a5aa27558a897b108e3be1a89859511a3fd26176dac292f26e7a4ae4?s=96&d=mm&r=g"}}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/posts\/418","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/comments?post=418"}],"version-history":[{"count":2,"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/posts\/418\/revisions"}],"predecessor-version":[{"id":421,"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/posts\/418\/revisions\/421"}],"wp:attachment":[{"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/media?parent=418"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/categories?post=418"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/practicalpowershell.com\/wp-json\/wp\/v2\/tags?post=418"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}