powershellexit-codereturn-codecommand-execution

Test integrity of archive with 7-Zip in PowerShell


I am trying to test integrity of ZIP file

It looks like this command is working but I got many details about the file. I want to get a result if the test passed or failed in order to move to the next step.

Any idea how to do it? Something like:

$TestZip = 7z t \\bandit\global\QA\AgileTeam\bandit\Builds\8.6.22.607\8.6.22.607.10.zip

if ($TestZip)
{The test passed}
else
{Test failed}

The output is:

Path = \\bandit\global\QA\AgileTeam\bandit\Builds\8.6.22.607\8.6.22.607.10.zip
Type = zip
Physical Size = 5738248794
64-bit = +
Characteristics = Zip64

Everything is Ok

Files: 902
Size:       5927324719
Compressed: 5738248794

Tried this:

$TestZip = 7z t \\bandit\global\QA\AgileTeam\bandit\Builds\8.6.22.607\8.6.22.607.10.zip | set out
$ok = $out -like '*Everything is Ok*'

if ($ok) {write-host "Integrity test for Zip file passed"}

Solution

  • Errors are reported via exit code so just check it. No need to parse the output, you can just redirect the output to null. The way to check exit status in PowerShell is $? and $LASTEXITCODE

    7z t $zip_file_path 2>$null 1>$null
    if ($?) {
        echo "Success"
    } else {
        echo "Failed"
    }
    

    Update:

    Use if ($LASTEXITCODE -eq 0) instead of if ($?) when stderr is redirected in older PowerShell (7.1.x and older) for more reliable result


    $?

    Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed.

    $LastExitCode

    Contains the exit code of the last native program that was run.

    about_Automatic_Variables