{"id":5450,"date":"2012-02-14T20:12:32","date_gmt":"2012-02-14T19:12:32","guid":{"rendered":"http:\/\/www.itwriting.com\/blog\/?p=5450"},"modified":"2012-02-14T20:12:32","modified_gmt":"2012-02-14T19:12:32","slug":"mysteries-of-trapping-errors-in-powershell","status":"publish","type":"post","link":"https:\/\/www.itwriting.com\/blog\/5450-mysteries-of-trapping-errors-in-powershell.html","title":{"rendered":"Mysteries of trapping errors in PowerShell"},"content":{"rendered":"<p>As everyone in IT knows, sometimes tasks that you think are quick and easy turn out to take longer.<\/p>\n<p>Today I experiences a small example. I have a scheduled PowerShell script that copies a large file. I wanted to enhance the script so that I would receive an email stating whether the copy succeeded and when it completed.<\/p>\n<p>The original script, for the sake of the example (it is actually a little more involved) is this:<\/p>\n<blockquote>\n<p>Copy-Item somefile somefile.bak      <br \/>&quot;Clean up&quot;<\/p>\n<\/blockquote>\n<p>where \u201cClean up\u201d represents some code that runs after the copy completes.<\/p>\n<p>Now, by default a PowerShell may continue if it hits an error other than a syntax error. Again for the sake of the example, I will add a line which echoes text to represent the code that send an email. If you run this script:<\/p>\n<blockquote>\n<p>Copy-Item somefile somefile.bak      <br \/>&quot;Clean up&quot;      <br \/>\u201dSend email: File copied successfully\u201d<\/p>\n<\/blockquote>\n<p>then the email gets sent whether or not the copy succeeds. Here is what happens if <em>somefile<\/em> does not exist:<\/p>\n<p><a href=\"http:\/\/www.itwriting.com\/blog\/wp-content\/uploads\/2012\/02\/image5.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px\" title=\"image\" border=\"0\" alt=\"image\" src=\"http:\/\/www.itwriting.com\/blog\/wp-content\/uploads\/2012\/02\/image_thumb5.png\" width=\"404\" height=\"206\" \/><\/a><\/p>\n<p>Not much use. The solution, I thought, was to use PowerShell\u2019s trap statement. This catches the exception you specify, or all exceptions, and runs some code. You can also use the <strong>break<\/strong> or <strong>continue<\/strong> keywords to determine whether the block of code in which the exception occurred continues with the next statement, or exits immediately. You can read about trap <a href=\"http:\/\/technet.microsoft.com\/en-us\/library\/dd347548.aspx\" target=\"_blank\">here<\/a>. I therefore wrote a script that looks like this:<\/p>\n<blockquote>\n<p>Function CopyIt {<\/p>\n<p>trap {return &quot;Error copying file: $_&quot;; break;}     <\/p>\n<p>Copy-Item somefile somefile.bak      <br \/>return &quot;Copy successfully completed&quot;      <br \/>}<\/p>\n<p>$result = CopyIt     <br \/>&quot;Clean up&quot;      <br \/>\u201dSend email: $result\u201d<\/p>\n<\/blockquote>\n<p>What I could not figure out though was that even when the copy failed, the script still sent me a success message:<\/p>\n<p><a href=\"http:\/\/www.itwriting.com\/blog\/wp-content\/uploads\/2012\/02\/image6.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px\" title=\"image\" border=\"0\" alt=\"image\" src=\"http:\/\/www.itwriting.com\/blog\/wp-content\/uploads\/2012\/02\/image_thumb6.png\" width=\"404\" height=\"206\" \/><\/a><\/p>\n<p>I assumed I was misunderstanding how trap works. The output shows, in this example, that an ItemNotFoundException is thrown, so the trap should be triggered, right?<\/p>\n<p>Wrong. In the case of non-terminating errors&#160; (PowerShell jargon) you have to specify the ErrorAction. The default ErrorAction is \u201cContinue\u201d. Therefore I had to modify the script like this:<\/p>\n<blockquote>\n<p>Copy-Item somefile somefile.bak -ErrorAction stop<\/p>\n<\/blockquote>\n<p>Now I get an email with a failure message if the copy fails:<\/p>\n<p><a href=\"http:\/\/www.itwriting.com\/blog\/wp-content\/uploads\/2012\/02\/image7.png\"><img loading=\"lazy\" decoding=\"async\" style=\"background-image: none; border-bottom: 0px; border-left: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top: 0px; border-right: 0px; padding-top: 0px\" title=\"image\" border=\"0\" alt=\"image\" src=\"http:\/\/www.itwriting.com\/blog\/wp-content\/uploads\/2012\/02\/image_thumb7.png\" width=\"404\" height=\"206\" \/><\/a><\/p>\n<p>All very obvious to PowerShell experts; but it seems to me that PowerShell makes it easy for the unwary to write scripts that fail silently. You are unlikely to see the red text when your script is running on a server.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As everyone in IT knows, sometimes tasks that you think are quick and easy turn out to take longer. Today I experiences a small example. I have a scheduled PowerShell script that copies a large file. I wanted to enhance the script so that I would receive an email stating whether the copy succeeded and &hellip; <a href=\"https:\/\/www.itwriting.com\/blog\/5450-mysteries-of-trapping-errors-in-powershell.html\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Mysteries of trapping errors in PowerShell<\/span> <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[80],"tags":[736,740],"class_list":["post-5450","post","type-post","status-publish","format-standard","hentry","category-software-development","tag-powershell","tag-programming"],"_links":{"self":[{"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/posts\/5450","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/comments?post=5450"}],"version-history":[{"count":0,"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/posts\/5450\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/media?parent=5450"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/categories?post=5450"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.itwriting.com\/blog\/wp-json\/wp\/v2\/tags?post=5450"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}