Creating Zip files using PowerShell

雨燕双飞 提交于 2019-12-02 08:12:53
Igor

You have two problems, I will try to summarize both of them.

1. Compress files

In order to use Compress-Archive command you need to have PowerShell 5 as already commented by @LotPings. You can:

  • run your script on Windows 10 machine, or Server 2016 which are coming with v5
  • download and install PoSh 5, see details on 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. Group files

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"
}

Pre Powershell v5 you can use this. No additional downloads needed.

$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()

With Powershell 2.0 you can't use Compress-Archive, you need download the original terminal executables to zip and unzip files from here.

You can use:

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

In your example:

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

If you need use adittional zip options, visit zip manual.

  • The following script does the grouping,
  • the zipping command depends on your chosen zipper.

$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
      }
}

Sample output:

> .\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

This link might help Module to Synchronously Zip and Unzip using PowerShell 2.0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!