title: How to return non zero exit code from a Powershell module function without closing the powershell console?
body: <p>My powershell module has a function and I want it to return a non zero exit code. However, being a module function it is loaded into the context of the powershell console when I run <code>Import-Module</code>. So, when the function executes <code>exit 1</code> - poof, goes the console window!</p>
  
  <p>At least, this is how I explain it closing the powershell window when it exits.</p>
  
  <p>So, how can a ps module function exit with a non zero exit code without killing the console where the module was imported?</p>
  
  <p>P.S.</p>
  
  <p>I did notice several questions on SO about this subject, but none seems to examine this particular case.</p>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>I would like to provide some context. I have a PS module with a lot of functions. Some of them are used as is in Azure DevOps yaml build scripts. The latter knows to recognize non zero exit code and abort the pipeline, so it is not necessary to throw from a function to abort the flow.</p>
  
  <p>However, if I want to call that function from the console, e.g. to test something quickly and it exits with non zero code, the whole console window is closed. This is extremely annoying.</p>
  
  <p>Sometimes there is a workaround. So, instead of this code:</p>
  
  <pre class="lang-bsh prettyprint-override"><code>dotnet build ...
  $ExitCode = $LastExitCode
  DoSomethingInAnyCase()
  if ($ExitCode)
  {
      exit $ExitCode
  }
  </code></pre>
  
  <p>We can have the following version:</p>
  
  <pre class="lang-bsh prettyprint-override"><code>try
  {
      dotnet build ...
  }
  finally
  {
      DoSomethingInAnyCase()
  }
  </code></pre>
  
  <p>Both versions would correctly return the right exit code, but because the second one does not have the explicit <code>exit</code> statement, it does not close the console.</p>