shellpowershellunzip

Powershell ParentContainsErrorRecordException on shell namespace


I'm trying to write an unzip powershell script, but I'm running into issues with the $shell.NameSpace() function.

function unzip ($sourceFile, $destination){
    $shell = new-object -com shell.application
    $zip = $shell.NameSpace($sourceFile)
    foreach($item in $zip.items()){
        $shell.Namespace($destination).copyhere($item) #Error here
    }
}

unzip "$PWD\folder.zip" $PWD

When I run this, I get an error on the second $shell.NameSpace() call.

You cannot call a method on a null-valued expression.
At C:\scriptDir\unzipScript.ps1:9 char:6
+         $shell.NameSpace($destination).copyhere($item)
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvokeMethodOnNull

What I dont understand is why this is failing on the second call. Clearly PWD exists and is a directory based on the first parameter.


Solution

  • Shell.NameSpace takes a string. $PWD is a PathInfo object. You can use $pwd.Path instead.

    unzip "$PWD\folder.zip" $PWD.Path
    

    As an alternative you can use the .Net System.IO.Compression.ZipFile class. Here is a sample.