title: Custom error from parameters in PowerShell
body: <p>Is it possible to have <code>ValidateScript</code> generate a custom error message when a test fails, like say <code>Test-Path</code>?</p>
  
  <p>Instead of this:</p>
  
  <blockquote>
    <p>Test-Folder : Cannot validate argument on parameter 'Folder'. The "Test-Path $_ -Path Type Container" validation script for the argument with value "blabla" did not return a result of True. Determine why the validation script failed, and then try the comma and again.</p>
  </blockquote>
  
  <p>It would be nice to have it report this instead in the <code>$Error</code> variable:</p>
  
  <blockquote>
    <p>The 'Folder' is not found, maybe there are network issues?</p>
  </blockquote>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>Function Test-Folder {
      Param (
          [parameter(Mandatory=$true)]
          [ValidateScript({Test-Path $_ -PathType Container})]
          [String]$Folder
      )
      Write-Host "The folder is: $Folder"
  }
  </code></pre>
  
  <p><strong>Workaround 1:</strong></p>
  
  <p>I could remove the <code>Mandatory=$true</code> and change it as below. But this doesn't give me the correct <code>Get-Help</code> syntax and doesn't do the <code>Test-Path</code> validation, because it only checks if the parameter is present.</p>
  
  <pre><code>Function Test-Folder {
      Param (
          [parameter()]
          [String]$Folder = $(throw "The $_ is not found, maybe there are network issues?")
      )
      Write-Host "The folder is: $Folder"
  }
  </code></pre>
  
  <p><strong>Workaround 2:</strong></p>
  
  <p>I found this workaround on <a href="http://mikefrobbins.com/2013/08/08/powershell-parameter-validation-building-a-better-validatepattern-with-validatescript/" rel="noreferrer">a blog post</a>, but the problem is that it generates two errors instead of one.</p>
  
  <pre><code>Function Test-Folder {
      Param (
          [parameter(Mandatory=$true)]
          [ValidateScript({
              if (Test-Path $_ -PathType Container) {$true}
              else {Throw "The $_ is not found, maybe there are network issues?"}})]
          [String]$Folder
      )
      Write-Host "The folder is: $Folder"
  }
  </code></pre>
  
  <p><strong>Workaround 3:</strong></p>
  
  <p>I <em>could</em> also try to make it more clear by adding a comment section. However, this is still not the desired result as the error needs to be readable to end users.</p>
  
  <pre><code>Function Test-Folder {
      Param (
          [parameter(Mandatory=$true)]
          [ValidateScript({
          # The folder is not found, maybe there are network issues?
          Test-Path $_ -PathType Container})]
          [String]$Folder
      )
      Write-Host "The folder is: $Folder"
  }
  </code></pre>