2

How do you count the files and folders in a zip file? I am running a verification of backups and need to compare the folder structure of the zip file against the folder structure of the windows folder is was made from. The final goal is to have a boolean value of if the source count is equal to the zip content count. This is as far as I have, so far:

 [Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') |out-null
 $ZipContents=[IO.Compression.ZipFile]::OpenRead($FilePath).Entries
 $ZipContents.Count

This gets a raw count of everything, but hoping for a distinct count of files and a count of folders or some way to compare structures. Using 7-zip would be fine, also. These zip files can get very large, so extracting first would be too time consuming to be an option.

Phoenix14830
  • 360
  • 1
  • 8
  • 24
  • Are you basing the success entirely on a count of folders/files, or are you also trying to ensure output file integrity is a 1:1 match on what was originally compressed? – gravity Aug 11 '17 at 20:29
  • The best solution would be to ensure the source and destination mirror each other, but a simple folder and file count would suffice. This is to be used after making a backup to confirm that the backup was successful. Testing that the zip file isn't corrupt isn't thorough enough of a validation. – Phoenix14830 Aug 11 '17 at 20:32
  • Actually, I was going to suggest checking the hash on each individual file and folder, then comparing against a similar hash on the original structure. – gravity Aug 11 '17 at 20:49

1 Answers1

3

If you can use 7z.exe, you may be able to do something like this:

& 'C:\Program Files\7-Zip\7z.exe' l <zipfilename> |
  Select-Object -Last 1 |
  Select-String '([0-9]+) files(?:, ([0-9]+) folders)?' |
  ForEach-Object {
    $fileCount = [Int] $_.Matches[0].Groups[1].Value
    $dirCount = [Int] $_.Matches[0].Groups[2].Value
  }
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62
  • Just a small note: If there are no folders in the , the value for files will not be retrieved. I assume, this happens because there is no comma after nnn files without found folders? – PeterCo Jul 26 '22 at 09:31
  • 1
    The regular expression in the original answer was lacking. I have updated the answer (try it again and see if it works). – Bill_Stewart Jul 26 '22 at 17:02