Java
Java

Reputation: 1292

Extract password protected 7z files using Powershell

I am trying to extract bunches of 7z files.

I was able to get these two sets of Powershell script from other Stackoverflow posts, but none of them seem to work.

$7ZipPath = '"C:\Program Files\7-Zip\7z.exe"'
$zipFile = '"F:\NHSFTP\WH_20240803_1.7z"'
$zipFilePassword = "xYxYxYx"
$command = "& $7ZipPath e -oe:\ -y -tzip -p$zipFilePassword $zipFile"
iex $command


$7ZipPath = '"C:\Program Files\7-Zip\7z.exe"'
$zipFile = '"F:\NHSFTP\WH_20240803_1.7z"'
$zipFilePassword = "xYxYxYx"
$command = "& $7ZipPath e -oW:\ADMINISTRATION -y -tzip -p$zipFilePassword $zipFile"
iex $command

What am I missing?

I am also trying to open multiple 7z files, not just one.

Do I express something like this?

$zipFile = '"F:\NHSFTP\*.7z"'

Update

Is this what I need to run (updated script)?

$7ZipPath = 'C:\Program Files\7-Zip\7z.exe'
$zipFile = 'F:\NHSFTP\WH_20240803_1.7z'
$zipFilePassword = 'xYxYxYx'
& $7ZipPath e -oe:\ -y -tzip -p$zipFilePassword $zipFile

Upvotes: 1

Views: 258

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60563

There is no reason to use Invoke-Expression here, I suggest creating a function that you can easily reuse later on. Also 7zip is capable of detecting the compression algorithm so you could just remove -tzip as argument.

function Expand-7zip {
    [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute(
        'PSAvoidUsingPlainTextForPassword', '')]
    param(
        [Parameter(Mandatory, ValueFromPipelineByPropertyName)]
        [Alias('FullName')]
        [string] $Path,

        [Parameter()]
        [string] $OutputPath,

        [Parameter()]
        [string] $Password
    )

    begin {
        $7z = 'C:\Program Files\7-Zip\7z.exe'
    }
    process {
        $params = @(
            'e'
            if ($OutputPath) {
                '-o' + $PSCmdlet.GetUnresolvedProviderPathFromPSPath($OutputPath)
            }
            '-y'
            $PSCmdlet.GetUnresolvedProviderPathFromPSPath($Path)
        )

        if ($Password) {
            $Password | & $7z @params
            return
        }

        & $7z @params
    }
}

Then you can use it like:

Expand-7zip F:\NHSFTP\WH_20240803_1.7z -OutputPath E:\ -Password xYxYxYx

And for extracting multiple files you can pipe the output from Get-ChildItem to this function (considering in this example all files have the same password):

Get-ChildItem F:\NHSFTP\ -Filter *.7z | Expand-7zip -Password xxxxx

Upvotes: 2

Related Questions