{"id":92538,"date":"2020-10-19T16:00:02","date_gmt":"2020-10-19T13:00:02","guid":{"rendered":"https:\/\/en.buradabiliyorum.com\/customizing-parameter-validation-errors-in-powershell-cloudsavvy-it\/"},"modified":"2020-10-19T16:00:02","modified_gmt":"2020-10-19T13:00:02","slug":"customizing-parameter-validation-errors-in-powershell-cloudsavvy-it","status":"publish","type":"post","link":"https:\/\/buradabiliyorum.com\/en\/customizing-parameter-validation-errors-in-powershell-cloudsavvy-it\/","title":{"rendered":"#Customizing Parameter Validation Errors In PowerShell \u2013 CloudSavvy IT"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_84 counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<label for=\"ez-toc-cssicon-toggle-item-6a2a9b136fa03\" class=\"ez-toc-cssicon-toggle-label\"><span class=\"\"><span class=\"eztoc-hide\" style=\"display:none;\">Toggle<\/span><span class=\"ez-toc-icon-toggle-span\"><svg style=\"fill: #dd3333;color:#dd3333\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" class=\"list-377408\" width=\"20px\" height=\"20px\" viewBox=\"0 0 24 24\" fill=\"none\"><path d=\"M6 6H4v2h2V6zm14 0H8v2h12V6zM4 11h2v2H4v-2zm16 0H8v2h12v-2zM4 16h2v2H4v-2zm16 0H8v2h12v-2z\" fill=\"currentColor\"><\/path><\/svg><svg style=\"fill: #dd3333;color:#dd3333\" class=\"arrow-unsorted-368013\" xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"10px\" height=\"10px\" viewBox=\"0 0 24 24\" version=\"1.2\" baseProfile=\"tiny\"><path d=\"M18.2 9.3l-6.2-6.3-6.2 6.3c-.2.2-.3.4-.3.7s.1.5.3.7c.2.2.4.3.7.3h11c.3 0 .5-.1.7-.3.2-.2.3-.5.3-.7s-.1-.5-.3-.7zM5.8 14.7l6.2 6.3 6.2-6.3c.2-.2.3-.5.3-.7s-.1-.5-.3-.7c-.2-.2-.4-.3-.7-.3h-11c-.3 0-.5.1-.7.3-.2.2-.3.5-.3.7s.1.5.3.7z\"\/><\/svg><\/span><\/span><\/label><input type=\"checkbox\"  id=\"ez-toc-cssicon-toggle-item-6a2a9b136fa03\" checked aria-label=\"Toggle\" \/><nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/buradabiliyorum.com\/en\/customizing-parameter-validation-errors-in-powershell-cloudsavvy-it\/#What_is_the_ErrorMessage_property\" >What is the ErrorMessage property?<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/buradabiliyorum.com\/en\/customizing-parameter-validation-errors-in-powershell-cloudsavvy-it\/#Extending_the_ErrorMessage_Functionality\" >Extending the ErrorMessage Functionality<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/buradabiliyorum.com\/en\/customizing-parameter-validation-errors-in-powershell-cloudsavvy-it\/#Further_Examples_of_Utilizing_ErrorMessage\" >Further Examples of Utilizing ErrorMessage<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/buradabiliyorum.com\/en\/customizing-parameter-validation-errors-in-powershell-cloudsavvy-it\/#Conclusion\" >Conclusion<\/a><\/li><\/ul><\/nav><\/div>\n<p><strong>&#8220;#Customizing Parameter Validation Errors In PowerShell \u2013 CloudSavvy IT&#8221;<\/strong><\/p>\n<div id=\"article-content-area\">\n<img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-4374\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/8fec593cd19e3b20a0773cafaaaaf848\/p\/uploads\/2020\/03\/23e4a5a4.png\" alt=\"Powershell logo\" width=\"1400\" height=\"578\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Error handling is often one of the most time consuming and tedious aspects of programming. PowerShell advanced functions have the very useful ability to leverage a multitude of ways to validate parameters before they are evaluated by the function as a whole. Avoiding bad data through parameter validation makes a programmer\u2019s job that much easier.<\/p>\n<p>In the past, errors that have been passed back to the user were not always very useful. Starting in PowerShell Core and continuing in PowerShell 7, the ability to define a custom error message has become possible. Instead of using a default error based on the parameter decoration, instead, you can define your own. Learn how to enhance your advanced functions to take advantage of this new functionality!<\/p>\n<h2><span class=\"ez-toc-section\" id=\"What_is_the_ErrorMessage_property\"><\/span>What is the <code>ErrorMessage<\/code> property?<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>You may have seen a parameter decorator such as <code>Validate<a href=\"https:\/\/buradabiliyorum.com\/en\/category\/download-scripts-themes-apps\/\" data-internallinksmanager029f6b8e52c=\"9\" title=\"Download Scripts &amp; Themes &amp; Apps\" target=\"_blank\" rel=\"noopener\">Script<\/a><\/code> before and, if used, found that the error message was not always the most descriptive. Often it is useful to craft your own message that more accurately reflects what the function is doing and why you may have an error. Three parameter validation decorators have the extra <code>ErrorMessage<\/code> property available to them.<\/p>\n<ul>\n<li><code>ValidateSet<\/code><\/li>\n<li><code>ValidateScript<\/code><\/li>\n<li><code>ValidatePattern<\/code><\/li>\n<\/ul>\n<p>What does this property actually do? First, let\u2019s look at the old way of doing this. In the example code below, we are using <code>ValidatePattern<\/code> to test if a string is 8 digits. If a fully-numeric string is not supplied, then we receive an error that could be considered cryptic and not very helpful to the user of your function.<\/p>\n<pre><code class=\"language-powershell\">Function Test-ValidatePattern {&#13;\n    [CmdletBinding()]&#13;\n    Param (&#13;\n        [ValidatePattern('^\\d{8}$')]&#13;\n        [String]$Digits&#13;\n    )&#13;\n&#13;\n    Process {&#13;\n      Write-Output $Digits&#13;\n    }&#13;\n}<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7401\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/1a52ab48a1d8b2cf14fd3029b6559c9f\/p\/uploads\/2020\/10\/a19ddbe2.png\" alt=\"\" width=\"1606\" height=\"223\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>Where does <code>ErrorMessage<\/code> come in then? Well, by simply adding in the additional property and specifying an error message to display to the end-user, we can make the function much more useful and user-friendly.<\/p>\n<pre><code class=\"language-powershell\">Function Test-ValidatePattern {&#13;\n    [CmdletBinding()]&#13;\n    Param (&#13;\n        [ValidatePattern('^\\d{8}$',ErrorMessage = \"Please use an 8 digit numeric value.\")]&#13;\n        [String]$Digits&#13;\n    )&#13;\n&#13;\n    Process {&#13;\n      Write-Output $Digits&#13;\n    }&#13;\n}<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7402\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/78fbe3d0d573d630251fa19bedcd47db\/p\/uploads\/2020\/10\/dc4d8986.png\" alt=\"\" width=\"1542\" height=\"239\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<h2><span class=\"ez-toc-section\" id=\"Extending_the_ErrorMessage_Functionality\"><\/span>Extending the <code>ErrorMessage<\/code> Functionality<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Utilizing the <code>ErrorMessage<\/code> parameter makes for a much more user-friendly error display. One aspect that is missing is the value that is passed in itself. In the original default error message, you may have noticed that both the value passed in and the validation regex pattern itself were shown in the error message. Thankfully, using a syntax similar to the format operator in PowerShell, we can include those values in our error message as well.<\/p>\n<ul>\n<li><code>{0}<\/code> \u2013 The passed in value.<\/li>\n<li><code>{1}<\/code> \u2013 The regex pattern.<\/li>\n<\/ul>\n<pre><code class=\"language-powershell\">Function Test-ValidatePattern {&#13;\n    [CmdletBinding()]&#13;\n    Param (&#13;\n        [ValidatePattern('^\\d{8}$',ErrorMessage = \"{0} is not an 8 digit numeric value fitting the pattern, {1}\")]&#13;\n        [String]$Digits&#13;\n    )&#13;\n&#13;\n    Process {&#13;\n      Write-Output $Digits&#13;\n    }&#13;\n}<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7403\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/a715bb54dc0e076cf7dd39aac05b3536\/p\/uploads\/2020\/10\/19a6a908.png\" alt=\"\" width=\"1443\" height=\"285\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>This syntax works on all three validation decorators and in the same way. The first formatting parameter is the text representation of the value being passed in while the second formatting parameter is either the set, script, or pattern that the value is being compared against.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Further_Examples_of_Utilizing_ErrorMessage\"><\/span>Further Examples of Utilizing <code>ErrorMessage<\/code><span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>To illustrate how using <code>ErrorMessage<\/code> within your <code>ValidateSet<\/code>, <code>ValidateScript<\/code>, and <code>ValidatePattern<\/code> decorators can further move the validation steps from within your begin or process blocks to the parameters themselves, let\u2019s take a look at a function utilizing all three parameter decorators.<\/p>\n<pre><code class=\"language-powershell\">Function Get-Computer {&#13;\n  [CmdletBinding()]&#13;\n  Param (&#13;\n    [ValidatePattern('^NET-\\d{8}$',ErrorMessage = \"{0} is not an 8 digit numeric value preceded by 'NET-' fitting the pattern, {1}\")]&#13;\n    [String]$ComputerName,&#13;\n&#13;\n    [ValidateSet('Desktop','Laptop','Mobile',ErrorMessage = \"{0} is not one of the allowed devices, {1}\")]&#13;\n    [String]$Type,&#13;\n&#13;\n    [ValidateScript({&#13;\n      $_ -GT (Get-Date)&#13;\n    },ErrorMessage = \"The expiration date, {0}, is not greater than the current date per the following script: {1}\")]&#13;\n    [DateTime]$ExpirationDate&#13;\n  )&#13;\n&#13;\n  Process {&#13;\n    [PSCustomObject]@{&#13;\n      \"ComputerName\" = $ComputerName&#13;\n      \"Type\"         = $Type&#13;\n      \"ExpireDate\"   = $ExpirationDate&#13;\n    }&#13;\n  }&#13;\n}&#13;\n<\/code><\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-7404\" src=\"https:\/\/www.cloudsavvyit.com\/thumbcache\/0\/0\/fdf40cb5d7417450710b2e8798cb0a2b\/p\/uploads\/2020\/10\/f122c6f9.png\" alt=\"\" width=\"1494\" height=\"344\" onload=\"pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\" onerror=\"this.onerror=null;pagespeed.lazyLoadImages.loadIfVisibleAndMaybeBeacon(this);\"\/><\/p>\n<p>As you can see, as each parameter was validated, the execution would stop if the value did not pass. If you supply multiple bad values, only the first one will actually error out and the following errors will not display until that value has been corrected.<\/p>\n<h2><span class=\"ez-toc-section\" id=\"Conclusion\"><\/span>Conclusion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n<p>Adding additional functionality for the <code>ValidateSet<\/code>, <code>ValidateScript<\/code>, and <code>ValidatePattern<\/code> parameter decorators is a big win for the usability of PowerShell advanced functions. Instead of cryptic error messages that are of minimal value to the user running the function, proper error messages can be shown that give insight as to what has gone wrong. This moves the error handling to a higher level than the begin or process blocks which makes for cleaner and more concise code.<\/p>\n<p>Since this functionality is available in PowerShell Core and PowerShell 7, you will need a newer version of PowerShell to take advantage of this functionality. With the upgrade comes numerous speed, security, and functionality benefits as well. Enhance your advanced functions with this useful property and make life easier for the users of your functions today!\n<\/p><\/div>\n<blockquote>\n<p style=\"text-align: center;\">For forums sites go to <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/forum.buradabiliyorum.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">Forum.BuradaBiliyorum.Com<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<blockquote>\n<p style=\"text-align: center;\"><strong>If you want to read more like this article, you can visit our <span style=\"color: #ff9900;\"><a style=\"color: #ff9900;\" href=\"https:\/\/en.buradabiliyorum.com\/technology\/\" target=\"_blank\" rel=\"noopener noreferrer\">Technology category.<\/a><\/span><\/strong><\/p>\n<\/blockquote>\n<p><span style=\"color: black;\"><a style=\"color: #ff9900;\" href=\"https:\/\/www.cloudsavvyit.com\/7399\/customizing-parameter-validation-errors-in-powershell\/\" target=\"_blank\" rel=\"noopener noreferrer\">Source<\/a><\/span><\/p>\n","protected":false},"excerpt":{"rendered":"<p>&#8220;#Customizing Parameter Validation Errors In PowerShell \u2013 CloudSavvy IT&#8221; Error handling is often one of the most time consuming and tedious aspects of programming. PowerShell advanced functions have the very useful ability to leverage a multitude of ways to validate parameters before they are evaluated by the function as a whole. Avoiding bad data through&#8230;<\/p>\n","protected":false},"author":1,"featured_media":92539,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"fifu_image_url":"https:\/\/www.cloudsavvyit.com\/p\/uploads\/2020\/03\/23e4a5a4.png","fifu_image_alt":"","footnotes":""},"categories":[18],"tags":[],"class_list":["post-92538","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-technology"],"_links":{"self":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/92538","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/comments?post=92538"}],"version-history":[{"count":0,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/posts\/92538\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media\/92539"}],"wp:attachment":[{"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/media?parent=92538"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/categories?post=92538"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/buradabiliyorum.com\/en\/wp-json\/wp\/v2\/tags?post=92538"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}