我正在制作一个更新一些文件的 Powershell(3.0 版,.Net 框架 4.5)脚本。但是,其中一些需要先进行检查。
我打开一个 JAR 文件并使用以下代码获取条目的内容:
[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
$zentry = [IO.Compression.ZipFile]::OpenRead($moduleJarPath).Entries | Where-Object {$_.FullName -match '.*pom.xml'}
该条目是使用 System.IO.StreamReader 读取的,该读取器在读取后立即关闭,位于 finally 块中。
在脚本的后面,我将用一个更新的 JAR 文件更新 JAR 文件,它可能具有相同的名称。在这种情况下,脚本会失败:
Copy-Item : The process cannot access the file 'E:\path\to\my\artifact.jar' because it is being used by another process.
看起来锁是由我自己的脚本持有的,这似乎合乎逻辑,因为我刚刚访问了 JAR。我想关闭句柄,以便我的脚本可以覆盖 JAR。
在 IO.Compression.ZipFile documentation ,没有“关闭”方法。
我怎样才能释放锁?
谢谢! :)
最佳答案
ZipArchive
,由 ZipFile.OpenRead()
返回, 实现 IDisposable
所以你会打电话Dispose()
例如
$zipFile = [IO.Compression.ZipFile]::OpenRead($moduleJarPath)
$zentry = $zipFile.Entries | Where-Object {$_.FullName -match '.*pom.xml'}
...
$zipFile.Dispose()
关于powershell - 在 Powershell 中,如何在 ZipFile.OpenRead 后关闭句柄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566682/