首页 > 解决方案 > 从类调用 [IO.Compression.ZipFile] 的 PowerShell 脚本的 ps2exe 转换后找不到类型 [IO.Compression.ZipFile]

问题描述

下面的 PowerShell(.ps1) 导致错误无法找到类型 [IO.Compression.ZipFile]。使用 ps2exe 将其转换为 (.exe) 后。从 ISE 以 (.ps1) 运行时,它工作正常。有谁知道出了什么问题?

#Requires -Assembly System.IO.Compression.FileSystem
Add-Type -AssemblyName System.IO.Compression.FileSystem

$f="myFile.zip"

Function displayZipContents ($f) {
#    Add-Type -AssemblyName System.IO.Compression.FileSystem

    $zipFile = [IO.Compression.ZipFile]::OpenRead($f)

    Write-Host "Contents of: $f"
    foreach($file in $zipFile.Entries) { 
        Write-Host "    ", (Join-Path $f $file.name)
    }

    $zipFile.Dispose()
}


class xyz {
    [string]$file # selected file or folder

     xyz ([string]$f) {
        $this.file = $f
     }

     [void] displayZipContents () {
        Add-Type -AssemblyName System.IO.Compression.FileSystem

        $zipFile = [IO.Compression.ZipFile]::OpenRead($this.file)

        Write-Host "Contents of: $this.file"
        foreach($file in $zipFile.Entries) { 
            Write-Host "    ", (Join-Path $this.file $file.name)
        }

        $zipFile.Dispose()
     }
}


displayZipContents $f # Works ok in (.ps1) and (.exe) after ps2exe conversion

$obj = New-Object xyz($f)
$obj.displayZipContents() # Works ok in (.ps1). But DOES NOT WORK in (.exe) after ps2exe conversion
<# Causes
ERROR: At line:43 char:21
+         $zipFile = [IO.Compression.ZipFile]::OpenRead($this.file)
+                     ~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [IO.Compression.ZipFile].
#>

标签: powershellclass

解决方案


推荐阅读