使用 PowerShell 创建 Zip 文件 [英] Creating Zip files using PowerShell
问题描述
我在 C:\Desktop\Mobile 的位置有以下这些文件.
I have these below files at a location C:\Desktop\Mobile.
Apple_iphone6.dat
Apple_iphone7.dat
Samsung_edge7.dat
Samsung_galaxy.dat
Sony_experia.dat
Sony_M2.dat
我需要创建一个脚本,将类似的文件写入一个 zip 文件.因此文件 Apple_iphone6.dat 和 Apple_iphone7.dat 必须为单个 zip.所以最终创建的 zip 文件将是:
I need to create a script that writes the similar files into a single zip. So files Apple_iphone6.dat and Apple_iphone7.dat must be into single zip. So the final zip files created would be:
Apple_Files_Timestamp.zip
Samsung_Files_Timestamp.zip
Sony_Files_Timestamp.zip
我试过了
Get-ChildItem C:\Desktop\Mobile -Recurse -File -Include *.dat | Where-Object { $_.LastWriteTime -lt $date } | Compress-Archive -DestinationPath C:\Desktop\Mobile
但它给了我错误Compress-Archive"不被识别为 cmdlet 的名称.
But it gives me error 'Compress-Archive' is not recognized as the name of a cmdlet.
我怎样才能让这个代码工作?
How can I get this code work?
推荐答案
你有两个问题,我会试着总结一下.
You have two problems, I will try to summarize both of them.
1.压缩文件
为了使用 Compress-Archive 命令,您需要拥有 PowerShell 5,正如@LotPings 所评论的那样.您可以:
In order to use Compress-Archive command you need to have PowerShell 5 as already commented by @LotPings. You can:
- 在 Windows 10 机器或 v5 随附的 Server 2016 上运行您的脚本
- 下载并安装 PoSh 5,详情请参见 MSDN
如果你不能做任何一个,你可以
If you cannot do either of those, you can
- install some module from PowerShell gallery that provides similar functionality via 7-zip tool. Search resultes are here. Download and check those modules before use!
- use .NET 4.5 class, check answer here on Stack Overflow
2.分组文件
一旦您对文件进行分组,您就可以轻松地将它们通过管道传输到压缩命令,就像您已经尝试过的那样.可以通过以下方式实现正确的分组:
Once you group files, you can easily pipe them to compressing command, similar as you already tried. Proper grouping would be achieved with something like this:
$Files = Get-ChildItem 'C:\Desktop\Mobile'
$Groups = $Files | ForEach-Object {($_.Name).split('_')[0]} | Select-Object -Unique
foreach ($Group in $Groups) {
$Files | where Name -Match "^$Group" | Compress-Archive "C:\Desktop\Mobile\$Group.7z"
}
这篇关于使用 PowerShell 创建 Zip 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!