title: PowerShell: detecting errors in script functions
body: <p>What is the best way to detect if an error occurs in a script function?  I'm looking for a consistent way to indicate error/success status similar to $? (which only works on cmdlets, not script functions).</p>
  
  <p>Given a particular function might return a value to be used by the caller, we can't indicate success by returning a boolean.  A function could use a [ref] parameter and set the value appropriately inside the function and check after the call, but this is more overhead than I'd like.  Is there something built-in to PowerShell that we can use?</p>
  
  <p>The best I can come up with is:</p>
  
  <ol>
  <li>In the function use Write-Error to 
  put ErrorRecord objects in the error 
  stream;</li>
  <li>call the function with an
  ErrorVariable parameter;</li>
  <li>check if the ErrorVariable parameter
  is not null after the call.</li>
  </ol>
  
  <p>For example:</p>
  
  <pre><code>function MyFun {
    [CmdletBinding()]    # must be an advanced function or this 
    param ()             # will not work as ErrorVariable will not exist
    process {
      # code here....
      if ($SomeErrorCondition) {
        Write-Error -Message "Error occurred; details..."
        return
      }
      # more code here....
    }
  }
  
  # call the function
  $Err = $null
  MyFun -ErrorVariable Err
  # this check would be similar to checking if $? -eq $false
  if ($Err -ne $null) {
    "An error was detected"
    # handle error, log/email contents of $Err, etc.
  }
  </code></pre>
  
  <p>Is there something better?  Is there a way of using $? in our script functions?  I'd rather not throw exceptions or ErrorRecord objects and have tons of try/catch blocks all over the place.  I'd also rather not use $Error as would require checking the count before making the function call as there could be other errors in there before the call - and I don't want to Clear() and lose them.</p>