我在PowerShell腳本中使用zip壓縮時遇到問題。有問題的代碼片段:使用加載程序集時Powershell錯誤
$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 [ERROR] lIDEInstallers \ VSInstallCBH.ps1:141 char:2 [錯誤] + $ mode = [System.IO.Compression.ZipArchiveMode] ::更新[錯誤] +
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~ [ERROR] + CategoryInfo:InvalidOperation: (System.IO.Compression.ZipArch [錯誤] iveMode:TypeName)[], RuntimeException [錯誤] + FullyQualifiedErrorId:TypeNotFound [錯誤]
但是,如果我再次運行它,它將正常工作。 我發現了幾篇文章(this和this),這些文章談到了類似的問題。我目前正在使用:
Add-Type -AssemblyName System.IO.Compression.FileSystem
在腳本的頂部。我也發現this post看起來很有希望,但沒有奏效。我還應該補充說明問題發生在ISE,Visual Studio和命令提示符中。如果我在任何環境中第二次運行該代碼,代碼將起作用。
我很困惑,不知所措。誰能告訴我爲什麼會發生這種情況?