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

时间:2016-05-30 06:59:04

标签: .net powershell zip powershell-v4.0

我知道有很多关于使用PowerShell编写文件的问题,但是尽管我进行了所有的搜索和测试,但我无法想出我需要的东西。

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

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

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

我尝试了不同的appraoches,如

$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(这将使我的生活变得如此简单)。

我很确定答案相当容易并且很明显,但我的大脑处于循环中,我无法弄清楚如何继续进行,所以任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:3)

您可以遍历已过滤文件的集合,并将它们逐个添加到存档中。

# 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()
相关问题