在 Powershell 中引用 .NET DLL

问题描述 投票:0回答:0

我目前需要在 powershell 脚本中解压缩一个文件,该脚本是使用 Ionic.Zip.Lib 压缩的,它是 DotNetZip 项目的一部分。所以我发现,用标准的 powershell 方式解压是不可能的

Expand-Archive C:\a.zip -DestinationPath C:\a

所以我决定在 powershell 中使用 c# 模板来完成这项工作

Add-Type -TypeDefinition $Source -ReferencedAssemblies @('System.IO', "D:\DotNetZip.dll", 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51') -Language CSharp 
$Source = @"
using Ionic.Zip;
using System.IO;
public class Unzipper
{
  public static void TryUnzipFile()
    {
        string zipfile = @"myPath\Test.zip";
        string dest = @"myPath\Test";
        string pw = "myPW";
        using (ZipFile zip = ZipFile.Read(zipfile))
        {
            zip.Password = pw;
            zip.ExtractAll(dest, ExtractExistingFileAction.OverwriteSilently);
        }
    }
}
"@
[Unzipper] | Get-Member -Static 

到目前为止一切顺利:

   TypeName: Unzipper

Name            MemberType Definition                                                         
----            ---------- ----------                                                         
Equals          Method     static bool Equals(System.Object objA, System.Object objB)         
new             Method     Unzipper new()                                                     
ReferenceEquals Method     static bool ReferenceEquals(System.Object objA, System.Object objB)
TryUnzipFile    Method     static void TryUnzipFile()                                         

但是当调用函数 TryUnzipFile() 时,我总是得到这个异常

[Unzipper]::TryUnzipFile()

Ausnahme beim Aufrufen von "TryUnzipFile" mit 0 Argument(en):  "Der Typeninitialisierer für "Ionic.Zip.ZipFile" hat eine Ausnahme verursacht."
In D:\inlinecode.ps1:31 Zeichen:1
+ [Unzipper]::TryUnzipFile()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : TypeInitializationException

有人可以帮我吗?

c# .net powershell
© www.soinside.com 2019 - 2024. All rights reserved.