Search code examples
bashpowershellzip

How to extract nested password protected zip folders using PowerShell a specified number of times?


I have a zip folder that contains a password{i}.txt file and a zip{i}.zip folder. I have to extract the password-protected zip using the password from password{i}.txt. Then, zip{i+1}.zip is also password protected (inside of zip{i}) and I have to do the same thing. Given 999 nested directories, I have to keep extracting until I reach a final answerthat is in a file.

The source code for doing this in bash is quite simple and easy to follow.

for ((i = 999 ; i >= 0 ; i--))
do
  pass=`cat password${i}.txt`
  rm password${i}.txt
  unzip -P $pass zip${i}.zip
  rm zip${i}.zip
done

I am learning PowerShell, but I am having trouble creating the code for it. How would I implement something similar using PowerShell? I am assuming the source is also quite short.


Solution

  • I solved this using multiple ways, but I had to download a dependency of some sort for the file extraction (with a password). I used 7Zip4Powershell and the code functions identical to the bash version.

    $curr = Get-Location 
    for ($i=999; $i-ge 0; $i--) {
        $pwd = [IO.File]::ReadAllText("password$i.txt"); 
        Expand-7Zip -ArchiveFileName "zip$i.zip" -TargetPath $curr -Password $pwd
        rm "password$i.txt"
        rm "zip$i.zip"
    }