1

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
J33nn
  • 3,034
  • 5
  • 30
  • 46
  • 1
    You are looking for something like this : http://stackoverflow.com/questions/10733718/is-there-a-way-to-catch-ctrl-c-and-ask-the-user-to-confirm But it is really hard to help without seeing any code – Cole9350 Apr 10 '14 at 14:53
  • I don't think I can use this solution in my code. I've added some code and error message to clarify a little. – J33nn Apr 10 '14 at 15:45
  • if your just trying to solve the problem of not having to open another terminal, I would just type $stream.close() into the console right after you cntrl+C ... then you can run the script again – Cole9350 Apr 10 '14 at 15:53

1 Answers1

1

Wrap file IO statements within a try...finally block and close() and dispose() the streamreader in the finalizer block.

vonPryz
  • 22,996
  • 7
  • 54
  • 65