繁体   English   中英

PowerShell-压缩文件夹中的特定文件

[英]PowerShell - Zip specific files in a folder

我知道有很多关于使用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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM