我正在使用PowerShell中的IO.Compression命名空间,并且遇到了一个问题,即我的C#代码中提供的方法在PowerShell中不可用
C#片段
string archfile = @"c:\temp\a1.zip";
string source = @"C:\temp\testing\logs\BatchProcess\BatchProcess_2017_08_22.log";
using (ZipArchive archive = ZipFile.Open(archfile, ZipArchiveMode.Update))
{
archive.CreateEntryFromFile(source, @"myfolder\folder2\file.log");
}
PowerShell中类似的代码启动
Add-Type -assembly System.IO.Compression.FileSystem
$archfile = "c:\temp\a1.zip"
# open mode: 1: Create, 2: Update
$archive = [System.IO.Compression.ZipFile]::Open("C:\temp\2.zip", 2)
$archive.CreateEntryFromFile($source, "myfolder\folder2\file.log")
对成员的审查表明缺少函数CreateEntryFromFile()等。该变量是一种ZipArchive,并创建了一个新文件
$archive | Get-Member
显示:
TypeName: System.IO.Compression.ZipArchive
Name MemberType Definition
---- ---------- ----------
CreateEntry Method System.IO.Compression.ZipArchiveEntry CreateEntry(string entryName), System.IO.Compression.ZipArchiveE...
Dispose Method void Dispose(), void IDisposable.Dispose()
Equals Method bool Equals(System.Object obj)
GetEntry Method System.IO.Compression.ZipArchiveEntry GetEntry(string entryName)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Entries Property System.Collections.ObjectModel.ReadOnlyCollection[System.IO.Compression.ZipArchiveEntry] Entries {get;}
Mode Property System.IO.Compression.ZipArchiveMode Mode {get;}
这仅仅是PowerShell如何创建.NET对象的一部分,而不是所有方法都支持(或可以)?
ZipArchive参考:https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive(v=vs.110).aspx
答案 0 :(得分:4)
{
if (studentmarks[i] < 40)
{
System.out.println(studentmarks[i]);
}
}
是一种扩展方法,因此它不会出现在Powershell中的CreateEntryFromFile
类中。
在Powershell 3.0或更高版本中,您可以声明在Powershell中使用的扩展方法。
ZipArchive
只需将扩展方法用作普通的旧静态方法。
Add-Type -AssemblyName System.IO.Compression.FileSystem
Update-TypeData -TypeName System.IO.Compression.ZipArchive -MemberType
ScriptMethod -MemberName CreateEntryFromFile -Value {
switch ($args.Count)
{
2 { [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($this, $args[0], $args[1]) }
3 { [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($this, $args[0], $args[1], $args[2]) }
default { throw "No overload for CreateEntryFromFile takes the specified number of parameters." }
}
}
$archfile = "c:\temp\a1.zip"
# open mode: 1: Create, 2: Update
$archive = [System.IO.Compression.ZipFile]::Open("C:\temp\2.zip", 2)
$archive.CreateEntryFromFile($source, "myfolder\folder2\file.log")
第二个选项是代码较少,也适用于旧版本的Powershell。
参考:How do I use extension methods in ZipFileExtensionsClass?