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

标签 powershell powershell-3.0

我正在制作一个更新一些文件的 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/

相关文章:

arrays - 如何使用 PowerShell 映射 2 个对象数组?

powershell - 编辑器面板中的visual-studio-code Powershell命令自动完成不起作用

linux - Linux和Windows之间的文本编码

powershell - 在文件的所有行中用 <space> 替换 ^M

powershell - 使用-notcontains在数组内的字符串中查找子字符串

xml - 使用 powershell 将文件夹结构转换为 XML 文件

powershell - 如何通过 Add-AzureAccount 使用 Microsoft(非组织)帐户?

c# - 使用 powershell 脚本通过 c# 重新启动应用程序池

winforms - Button.add_click 中带有变量的启动进程文件路径将无法按预期工作

shell - 如何从 PowerShell 快捷方式启动带有 "default"颜色的 powershell.exe?