脚本终止时释放文件句柄

时间:2014-04-10 14:44:35

标签: powershell

如何强制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:\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

1 个答案:

答案 0 :(得分:1)

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