脚本终止时释放文件句柄



如何强制powershell在脚本终止CTRL-C时释放文件句柄。在部分测试脚本时,由于文件句柄的原因,我必须重新启动powershell才能再次执行脚本。当我终止脚本时,有什么方法可以释放它吗?

$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

当我在处理脚本的REST部分时终止脚本时,下次执行脚本时,我会收到以下错误消息:

Cannot convert value "testfile" to type "System.IO.StreamWriter". Error: "The process cannot access the file 'C:Usersj33nntestfile' because it is being used by another process.
"At C:Usersj33nnDocumentsworktestscript.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:Usersj33nnDocumentsworktestscript.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:Usersj33nnDocumentsworktestscript.ps1:64 char:18
+ $stream.WriteLine <<<< ("")
+ CategoryInfo          : InvalidOperation: (WriteLine:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

将文件IO语句包装在try...finally块中,并将close()dispose()包装在终结器块中的流读取器中。

最新更新