使用 PowerShell 创建 Zip 文件

Creating Zip files using PowerShell

我在 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 文件将是:

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 的名称。

我怎样才能让这段代码工作?

对于 Powershell 2.0,您不能使用 Compress-Archive,您需要下载原始终端可执行文件来压缩和解压缩来自 here 的文件。

您可以使用:

zip <path> <zip_name> -i <pattern_files>

在你的例子中:

zip "C:\Desktop\Mobile" Apple_Files_Timestamp.zip -i Apple*.dat
zip "C:\Desktop\Mobile" Samsung_Files_Timestamp.zip -i Samsung*.dat
zip "C:\Desktop\Mobile" Sony_Files_Timestamp.zip -i Sony*.dat

如果您需要使用其他 zip 选项,请访问 zip manual

您可以使用 Pre Powershell v5。无需额外下载。

$FullName = "Path\FileName"
$Name = CompressedFileName
$ZipFile = "Path\ZipFileName"
$Zip = [System.IO.Compression.ZipFile]::Open($ZipFile,'Update')
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Zip,$FullName,$Name,"optimal")
$Zip.Dispose()

你有两个问题,我会尽量总结一下。

1.压缩文件

为了使用 Compress-Archive 命令,您需要安装 PowerShell 5,正如@LotPings 所评论的那样。您可以:

  • 运行 您在 Windows 10 机器上的脚本,或随 v5
  • 一起提供的 Server 2016
  • 下载并安装 PoSh 5,详情见 MSDN

如果你做不到其中任何一个,你可以

  • 从 PowerShell 库中安装一些模块,这些模块通过 7-zip 工具提供类似的功能。搜索结果为 here。使用前下载并检查这些模块!
  • 使用 .NET 4.5 class,在 Stack Overflow
  • 上查看 answer

2。组文件

一旦你对文件进行分组,你就可以轻松地将它们通过管道传输到压缩命令,就像你已经尝试过的那样。正确的分组可以通过这样的方式实现:

$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"
}
  • 以下脚本进行分组,
  • 压缩命令取决于您选择的拉链。

$TimeStamp = Get-Date -Format "yyyyMMddhhmmss"
Get-ChildItem *.dat|
  Group-Object {($_.Name).split('_')[0]}|
    ForEach-Object {
      $Make = $_.Name
      Foreach($File in $_.Group){
        "{0,20} --> {1}_Files_{2}.zip" -f $File.Name,$Make,$TimeStamp
      }
}

示例输出:

> .\SO_44030884.ps1
   Samsung_edge7.dat --> Samsung_Files_20170517081753.zip
  Samsung_galaxy.dat --> Samsung_Files_20170517081753.zip
   Apple_iphone6.dat --> Apple_Files_20170517081753.zip
   Apple_iphone7.dat --> Apple_Files_20170517081753.zip
         Sony_M2.dat --> Sony_Files_20170517081753.zip
    Sony_experia.dat --> Sony_Files_20170517081753.zip

这个 link 可能会有所帮助 Module to Synchronously Zip and Unzip using PowerShell 2.0