2016-06-29 32 views
1

我在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 [錯誤]

但是,如果我再次運行它,它將正常工作。 我發現了幾篇文章(thisthis),這些文章談到了類似的問題。我目前正在使用:

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

在腳本的頂部。我也發現this post看起來很有希望,但沒有奏效。我還應該補充說明問題發生在ISE,Visual Studio和命令提示符中。如果我在任何環境中第二次運行該代碼,代碼將起作用。

我很困惑,不知所措。誰能告訴我爲什麼會發生這種情況?

回答

1

戴夫的回答是部分線索的決議。按照他的建議更改Add-Type命令可以讓事情變得更好。但是,代碼仍然失敗了,因爲他現在提出的修改導致了這個命令:

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

失敗。

我能夠糾正和解決問題,一旦我發現:

要使用的擴展方法,你必須引用 System.IO.Compression.FileSystem組件項目。

與戴維的建議,我只是增加了以下改正我的問題:

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

現在的代碼工作正常第一次。

2

你很近。在這種情況下,您需要再加載一個程序集。使用:

Add-Type -AssemblyName System.IO.Compression 
相關問題