0

I'd like to write a PowerShell script to extract multiple password-protected .7z files, that have their passwords saved inside a text file that its filename contains the name of the .7z

File structure example:

EncryptedFile1_02192020.7z

EncryptedFile1_password.txt

EncryptedFile2_02192020.7z

EncryptedFile2_password.txt

The script below works only if there are 1 .7z and 1 .txt file in the folder.

$pass = get-content *.txt
7z.exe x *.7z -p"$pass" -o*

Problem: I do not know how to use the combination of foreach and -Like statements to batch extract multiple encrypted files in the working directory. Thanks in advance for your help.

Bijan
  • 3
  • 3
  • A Google search for `ForEach Get-ChildItem` returns [This Stack Question](https://stackoverflow.com/questions/11568221/using-foreach-with-get-childitem-recurse) which should help you. Just ignore the -Recurse suggestion if all your files are in one subdirectory. – Matthew Feb 19 '20 at 23:41

1 Answers1

0

Here's one method. It gathers the files inside the rootfolder, groups them on the first part of the filename before the underscore _ and finds the files ending in .txt and .7z inside these groups.
If we have both, the password is read from the text file and the 7z file is extracted.

Get-ChildItem -Path 'TheFolderWhereTheFilesAre' -File | 
    Group-Object @{Expression = {($_.Name -split '_')[0]}} |
    Where-Object { $_.Count -gt 1 } | 
    ForEach-Object {
        $pwFile = $_.Group | Where-Object { $_.Extension -eq '.txt' }
        $7zFile = $_.Group | Where-Object { $_.Extension -eq '.7z' }
        if (($pwFile) -and ($7zFile)) {
            Write-Host "Extracting file '$($7zFile.FullName)'"
            # the single quotes are needed when the password contains spaces or special characters
            $pass = "'{0}'" -f (Get-Content -Path $pwFile.FullName -Raw)
            7z.exe x $($7zFile.FullName) -p"$pass" -o* 
    }
}

Note, If the files all start with EncryptedFile_, then you can add -Filter 'EncryptedFile_*.*' to the Get-ChildItem cmdlet to speed things up

Theo
  • 57,719
  • 8
  • 24
  • 41