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