How to force powershell to release file handle on script termination CTRL-C
. 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?
$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
When I terminate script during working on REST part of script, next time I execute the script I've got this error message:
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 <<<<
+ 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 <<<< ("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 <<<< ("")
+ CategoryInfo : InvalidOperation: (WriteLine:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull