.net - PowerShell - 将特定文件压缩到文件夹中

标签 .net powershell zip powershell-4.0

我知道有很多关于使用 PowerShell 压缩文件的文章(和询问),但尽管我进行了所有搜索和测试,我还是无法找到我需要的内容。

根据主题,我正在编写一个脚本,用于检查目录中是否有在特定时间范围内创建的文件

   $a= Get-ChildItem - path $logFolder | 
Where-Object {$_.CreationDate -gt $startDate -and $_.CreationDate -lt $endDate}

虽然我可以获得我想要/需要的文件列表,但我找不到将它们发送到 zip 文件的方法。

我尝试过不同的方法,例如

$sourceFolder = "C:\folder1"
$destinationZip = "c:\zipped.zip" 
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolder, $destinationZip)

但是,虽然这在压缩文件夹时效果很好,但它不是我想要的,当然我可以将文件移动到临时文件夹并压缩,但这看起来很浪费,我确信有更好的方法这。

请记住,我无法使用 7zip 等第三方工具,我无法使用 PowerShell 扩展或 PowerShell 5(这将使我的生活变得更加轻松)。

我很确定答案相当简单且显而易见,但我的大脑处于循环状态,我不知道如何继续,因此我们将不胜感激。

最佳答案

您可以循环浏览已过滤文件的集合,并将它们逐一添加到存档中。

# creates empty zip file:
[System.IO.Compression.ZipArchive] $arch = [System.IO.Compression.ZipFile]::Open('D:\TEMP\arch.zip',[System.IO.Compression.ZipArchiveMode]::Update)
# add your files to archive
Get-ChildItem - path $logFolder | 
Where-Object {$_.CreationDate -gt $startDate -and $_.CreationDate -lt $endDate} | 
foreach {[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($arch,$_.FullName,$_.Name)}
# archive will be updated with files after you close it. normally, in C#, you would use "using ZipArchvie arch = new ZipFile" and object would be disposed upon exiting "using" block. here you have to dispose manually:
$arch.Dispose()

关于.net - PowerShell - 将特定文件压缩到文件夹中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37519439/

相关文章:

c# - 如何获取 GridView 上 DataSet.DataTable 的总计?

powershell - 在 Powershell 中应该使用什么异常类型来捕获由于无效字符引起的 XML 解析错误?

powershell - Azure 自动化中的 ADAL : Type not loading intermittantly

c# - WPF 安装部署项目

c# - 通过命名数组提供内部列表访问

Github 下载文件夹为 zip

java - 将 ZipEntry 复制到新 ZipFile 的惯用方法是什么?

iphone - 我可以在 ios 应用程序中的 NSMainBundle 中创建文件吗?这段代码的含义是什么?

c# - 将泛型类型传递给采用泛型类型的方法

powershell - 将 powershell Select-Object 与包含方括号的属性一起使用