【问题标题】:Powershell error when using loaded assembly使用加载的程序集时出现 Powershell 错误
【发布时间】:2016-06-29 22:43:26
【问题描述】:

我在 Powershell 脚本中使用 zip 压缩时遇到问题。有问题的代码 sn-p 是:

$zipfile = $targetFile
$file   = 'Script.ps1'

$stream = New-Object IO.FileStream($zipfile, [IO.FileMode]::Open)
$mode   = [System.IO.Compression.ZipArchiveMode]::Update
$zip    = New-Object IO.Compression.ZipArchive($stream, $mode)

($zip.Entries | ? { $file -contains $_.Name }) | % { $_.Delete() }

#   Add a newer Script.ps1 file with the new Comment Based Help template.
$newFile = "$PSScriptRoot\$file"
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$newFile,"Script.ps1","optimal")

#   Clean up.
$zip.Dispose()
$stream.Close()
$stream.Dispose()

代码尝试从存档中删除文件,然后添加同一文件的更新版本。当我运行脚本时,我收到以下信息:

[错误] 找不到类型 [System.IO.Compression.ZipArchiveMode]。 确保包含此类型的 [ERROR] 程序集是 加载。 [错误] 在 C:\xxxxx\xxxxx\xxxxx\PowerShellIDEInstallers\PowerShel [错误] lIDEInstallers\VSInstallCBH.ps1:141 char:2 [错误] + $mode = [System.IO.Compression.ZipArchiveMode]::Update [错误] +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~ [错误] + 类别信息:无效操作: (System.IO.Compression.ZipArch [错误] iveMode:TypeName) [], RuntimeException [错误] + FullyQualifiedErrorId:TypeNotFound [错误]

但是,如果我再次运行它,它将正常工作。 我发现一些帖子(thisthis)谈到了类似的问题。我目前正在使用:

Add-Type -AssemblyName System.IO.Compression.FileSystem

在脚本的顶部。我还发现 this post 看起来很有希望,但是没有用。我还应该补充一点,问题发生在 ISE、Visual Studio 和命令提示符中。如果我在任何环境中再次运行该代码,该代码将起作用。

我很困惑,不知所措。谁能告诉我为什么会这样?

【问题讨论】:

    标签: .net powershell zip


    【解决方案1】:

    你已经接近了。在这种情况下,您需要再加载一个程序集。使用:

    Add-Type -AssemblyName System.IO.Compression
    

    【讨论】:

      【解决方案2】:

      戴夫的回答是解决问题的部分线索。按照他的建议更改Add-Type 命令会使事情变得更好。但是,代码仍然失败,因为他现在建议的更改导致了命令:

      [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,$newFile,"Script.ps1","optimal")
      

      失败。

      一旦发现问题,我就能纠正并解决问题:

      要使用扩展方法,您必须引用 项目中的 System.IO.Compression.FileSystem 程序集。

      根据 Dave 的建议,我简单地添加了以下内容来纠正我的问题:

      Add-Type -AssemblyName System.IO.Compression
      Add-Type -AssemblyName System.IO.Compression.FileSystem
      

      代码现在第一次可以正常工作。

      【讨论】:

        猜你喜欢
        • 2022-01-04
        • 2022-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多