【问题标题】:Release file handle on script terminate在脚本终止时释放文件句柄
【发布时间】:2014-04-10 23:50:33
【问题描述】:

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

【问题讨论】:

  • 你正在寻找这样的东西:stackoverflow.com/questions/10733718/… 但是如果没有看到任何代码真的很难提供帮助
  • 我认为我不能在我的代码中使用这个解决方案。我添加了一些代码和错误消息来澄清一下。
  • 如果您只是想解决不必打开另一个终端的问题,我只需在您 cntrl+C 之后在控制台中键入 $stream.close() ...然后您就可以运行再次编写脚本

标签: powershell


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2011-02-10
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多