title: How do I clear $error and $LASTEXITCODE set by an external cmdlet or executable?
body: <p>I have a custom module wrapping an external command (<code>csrun.exe</code>), and parses the output so I can use it in PowerShell. </p>
  
  <p>Everything just about works except if the external command writes to <code>stderror</code>, and clearing the error in my cmdlet doesn't seem to fully work. It will clear (i.e. <code>$error.count</code> is <code>0</code> and <code>$lasterrorcode</code> is <code>0</code>, but once I return to the script that is calling my cmdlet, <code>$error</code> and <code>$lasterrorcode</code> are no longer clear and the error in <code>$error</code> references the underlying exception for the external command </p>
  
  <pre><code>System.Management.Automation.RemoteException: The compute emulator is not running.
  </code></pre>
  
  <p>I've attempted, try-catches, clearing the mentioned variables. Regardless, the calling script retains a reference to the error.</p>
  
  <h2>CustomModule.psm1</h2>
  
  <pre class="lang-ps prettyprint-override"><code>$__azureEmulatorPath = "C:\Program Files\Microsoft SDKs\Azure\Emulator\"SDKs\Azure\Emulator\"
  $__azureEmulator = __azureEmulatorPath + "csrun.exe"
  
  function Get-EmulatorStatus() {
      [OutputType([ComputeEmulatorStatus])] 
      [cmdletbinding()]
      param()
  
      $output = (&amp; $__azureEmulator /status | Out-String)
  
      if ($error.Count -gt 0 -or $LASTEXITCODE -ne 0) {
          Write-Host ($Error | Format-List -Force | Out-String)
          Write-Host Clearing Error and Continuing
          $error.Clear()
          $LASTEXITCODE = 0
      }
  
      #error from command cleared here
  
      return $output
  }
  
  export-modulemember -function *
  </code></pre>
  
  <h2>Test.ps1</h2>
  
  <pre><code>import-module "CustomModule.psm1" # definew cmdlet Get-EmulatorStatus
  
  $status = Get-EmulatorStatus
  
  # even though error cleared in cmdlet, still here
  Write-Host Write-Host Error $LASTEXITCODE, $Error.Count
  Write-Host ($Error | Format-List -Force | Out-String)
  </code></pre>