在Powershell中,如何在ZipFile.OpenRead之后关闭句柄?

Séb*_*ien 5 powershell powershell-3.0

我正在制作一个更新一些文件的Powershell(3.0版,.Net framework 4.5)脚本.但是,有些需要先进行检查.

我打开一个JAR文件并使用以下代码获取条目的内容:

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
$zentry = [IO.Compression.ZipFile]::OpenRead($moduleJarPath).Entries | Where-Object {$_.FullName -match '.*pom.xml'}
Run Code Online (Sandbox Code Playgroud)

使用System.IO.StreamReader读取该条目,该读取在读取后立即在finally块中关闭.

在脚本的下方,我将使用更新的JAR文件更新,该文件可能具有相同的名称.在这种情况下,脚本失败:

Copy-Item : The process cannot access the file 'E:\path\to\my\artifact.jar' because it is being used by another process.
Run Code Online (Sandbox Code Playgroud)

看起来锁是由我自己的脚本保存的,这似乎是合乎逻辑的,因为我刚刚访问了JAR.我想关闭句柄,以便我的脚本可以覆盖JAR.

在IO.Compression.ZipFile 文档中,没有"关闭"方法.

我怎样才能解锁?

谢谢!:)

Kei*_*ill 14

ZipArchive,返回ZipFile.OpenRead(),实现IDisposable所以你会打电话给Dispose()例如

$zipFile = [IO.Compression.ZipFile]::OpenRead($moduleJarPath)
$zentry = $zipFile.Entries | Where-Object {$_.FullName -match '.*pom.xml'}
...
$zipFile.Dispose()
Run Code Online (Sandbox Code Playgroud)