title: $Error variable in a Powershell Script Module/ Commandlet
body: <p>First, let me start off with what I want to achieve.</p>
  
  <p>I am writing a PowerShell Script Module (let's call it Get-FdkUser) that's internally calling Get-AdUser and should retry a couple of times in case every but a certian Exception is thrown. Of course, because it's retrying, the error should not be logged -- it's only an error if the retries don't work.
  This PowerShell Script Module is used as part of a script to go through >100,000 users. In addition to AD data, I am pulling in data from Exchange and AzureAD. </p>
  
  <p>Before implementing the retries, I was recording any kind of error by checking the $Error variable. Basically like this</p>
  
  <pre><code>$Error.clear()
  Get-ADUser
  Get-Mailbox
  Get-AzureADUser
  if($Error.Count -gt 0) {
    Do something
  }
  </code></pre>
  
  <p>Works like a charm.</p>
  
  <p>Now, my issue...</p>
  
  <p><strong>1)</strong> In a PowerShell Script Module, the $Error variable doesnt seem to be populated. It's only populated after execution of the commandlet.
  You can replicate this by checking the following code.
  I find this odd even without my requirement. It seems I can never use the $Error variable in a PowerShell Script Module?</p>
  
  <p><strong>File: ErrorTest.psm1</strong></p>
  
  <pre><code>function Get-FdkTest
  {
    [CmdletBinding()]
    Param
    ()
  
    try {
        $temp[-1]
    } catch {
        Write-Host "there was an error"
    }
    Write-Host "Commandlet error count $($Error.Count)"
  
  }
  Export-ModuleMember -Function *
  </code></pre>
  
  <p><strong>Script</strong></p>
  
  <pre><code>Import-Module .\ErrorTest.psm1 -Force
  $Error.Clear()
  Get-FdkTest
  "Error count outside of commandlet $($Error.Count)"
  </code></pre>
  
  <p><strong>Output</strong></p>
  
  <pre><code>there was an error
  Commandlet error count 0
  Error count outside of commandlet 1
  </code></pre>
  
  <p><strong>2)</strong> As mentioned, Exceptions that can be fixed with retries shouldnt even surface up. Ideally I would like to remove them from the $Error variable or avoid them from being captured. Besides this not working anyway due to 1), there is maybe a better way to tackle this.</p>
  
  <p>Lastly, here is the PowerShell version I am running.</p>
  
  <pre><code>Name                           Value
  ----                           -----
  PSVersion                      5.1.15063.1029
  PSEdition                      Desktop
  PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
  BuildVersion                   10.0.15063.1029
  CLRVersion                     4.0.30319.42000
  WSManStackVersion              3.0
  PSRemotingProtocolVersion      2.3
  SerializationVersion           1.1.0.1
  </code></pre>