Search code examples
powershellif-statementunzippowershell-4.0

Test if zip File extract command executed


I want to test if condition for zip file got extracted properly or any error in extracting command in PowerShell v4. Please correct my code.

Add-Type -AssemblyName System.IO.Compression.FileSystem

$file = 'C:\PSScripts\raw_scripts\zipfold\test.zip'
$path = 'C:\PSScripts\raw_scripts\zipfold\extract'

if ( (Test-path $file) -and (Test-path $path) -eq $True ) {
    if ((unzip $file $path)) {
        echo "done with unzip of file"
    } else {
        echo "can not unzip the file"
    }
} else {
    echo "$file or $path is not available"
}

function unzip {
    param([string]$zipfile, [string]$outpath)

    $return = [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
    return $return
}

This script extract a zip file but displays "can not unzip file." as output.

Not sure what $return variable has as its value, my If condition is always getting fail.


Solution

  • The documentation confirms what @Matt was suspecting. ExtractToDirectory() is defined as a void method, so it doesn't return anything. Because of that $return is always $null, which evaluates to $false.

    With that said, the method should throw exceptions if something goes wrong, so you could use try/catch and return $false in case an exception occurs:

    function unzip {
      param([string]$zipfile, [string]$outpath)
    
      try {
        [IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
        $true
      } catch {
        $false
      }
    }