Home > Blockchain >  Compress files with same name in powershell
Compress files with same name in powershell

Time:04-30

I have a folder with more than 1000 file extensions.

This is a sample of my files.

  • AFG.cpg
  • AFG.dbf
  • AFG.prj
  • AFG.sbn
  • AFG.sbx
  • AFG. shp
  • AFG.shx
  • AFG.cpg
  • AGO.dbf
  • AGO.prj
  • AGO.sbn
  • AGO.sbx
  • AGO. shp
  • AGO.shx

I want to zip them according to the first 3 letters. For the sample, I am looking to get two zip files, one for AFG.zip, and AGO.zip.

I was able to compress one file using the following, but the resulting folder returns with the directory name "countries" instead of the file name:

$compress = @{
LiteralPath= "C:\Countries"
CompressionLevel = "Fastest"
DestinationPath = "C:\Countries\Draft.Zip"
}
Compress-Archive @compress

I also tried the following to group the files and compress them:

Get-ChildItem C:\Countries | 
    Group-Object -Property { $_.Name.Substring(0, 3) } |
    % { Compress-Archive -Path $_.Group -DestinationPath "$($_.Name).zip" }

But I am getting the following errors:

[ERROR] Compress-Archive : The path 'AFG.cpg' either does not exist or is not a valid file system
path.
[ERROR] At line:3 char:9
      % { Compress-Archive -Path $_.Group -DestinationPath "$($_.Name). ...
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      CategoryInfo          : InvalidArgument: (AFG.cpg:String) [Compress-Archive], InvalidO
   perationException
      FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive

I believe the error has to do with the third line: > { Compress-Archive -Path $.Group -DestinationPath "$($.Name).zip" }, but not sure how to fix it. I also tried some other code to do this, as this is kind of a popular question but they don't seem to work. I just started to use powershell for this, thank you for any help.

I am using powershell x86.

CodePudding user response:

I just tried your code:

Get-ChildItem C:\temp\|
Group-Object -Property { $_.Name.Substring(0, 3) } |
ForEach-Object { Compress-Archive -Path $_.Group -DestinationPath "$($_.Name).zip" }

It worked totally fine for me.

Can you may add some further information:

Powershell Version Session Path Location

etc.

CodePudding user response:

I was able to zip each of my files thanks to @guiwhatsthat comment. This is the fixed code:

Get-ChildItem C:\Folder | 
    Group-Object -Property { $_.Name.Substring(0, 3) } |
    % { Compress-Archive -Path $_.Group.FullName -DestinationPath "$($_.Name).zip" }
  • Related