Reputation: 39
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.
Upvotes: 0
Views: 2067
Reputation: 200303
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
}
}
Upvotes: 0