title: Release file handle on script terminate
body: <p>How to force powershell to release file handle on script termination <code>CTRL-C</code>. While partially testing script I have to restart powershell in order to execute script again because of file handle. Is there any way to release it when I terminate script?</p>
  
  <pre><code>$outFile = 'testfile'
  $stream = [System.IO.StreamWriter] $outFile
  $stream.WriteLine("Some txt")
  ... // here is body of script which can take a lot of time
  ... // this calls external REST services and output some info to 
  ... // opened file.
  $stream.close()
  Exit
  </code></pre>
  
  <p>When I terminate script during working on REST part of script, next time I execute the script I've got this error message:</p>
  
  <pre><code>Cannot convert value "testfile" to type "System.IO.StreamWriter". Error: "The process cannot access the file 'C:\Users\j33nn\testfile' because it is being used by another process.
  "At C:\Users\j33nn\Documents\work\testscript.ps1:62 char:44
  + $stream = [System.IO.StreamWriter] $outFile &lt;&lt;&lt;&lt;
  + CategoryInfo          : NotSpecified: (:) [], RuntimeException
  + FullyQualifiedErrorId : RuntimeException
  
  You cannot call a method on a null-valued expression.
  At C:\Users\j33nn\Documents\work\testscript.ps1:63 char:18
  + $stream.WriteLine &lt;&lt;&lt;&lt; ("Some txt")
  + CategoryInfo          : InvalidOperation: (WriteLine:String) [], RuntimeException
  + FullyQualifiedErrorId : InvokeMethodOnNull
  
  You cannot call a method on a null-valued expression.
  At C:\Users\j33nn\Documents\work\testscript.ps1:64 char:18
  + $stream.WriteLine &lt;&lt;&lt;&lt; ("")
  + CategoryInfo          : InvalidOperation: (WriteLine:String) [], RuntimeException
  + FullyQualifiedErrorId : InvokeMethodOnNull
  </code></pre>