Search code examples
powershelluser-accounts

PowerShell Unzip Access Denied


I have a PowerShell script that is supposed to unzip some files in a directory, but when I run it it throws this error:

Exception calling "ExtractToDirectory" with "2" argument(s): "Access to the path 
'E:\SubFolder\SubFolder2\SubFolder3' is denied."
At line:7 char:5
+     [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, "E:\SubFolder\Sub ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : UnauthorizedAccessException

I have given myself full control to each individual folder in the path and run as administrator (just to test) and it still throws the error.

Here is my code

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

function Unzip
{
    param([string]$zipfile)

    [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, "E:\SubFolder\SubFolder2\SubFolder3")

}

$Files = get-childitem "E:\SubFolder\SubFolder2\SubFolder3"

foreach ( $i in $files ) 
{
    Unzip "SubFolder\SubFolder2\SubFolder3\$i" 
}

Could someone point me in the right direction to get this working?


Solution

  • Add a Where in the Get-ChildItem

    Get-ChildItem "E:\SubFolder\SubFolder2\SubFolder3" | Where { $_.Extension -eq ".zip" }
    

    I would also suggest you change the argument when calling Unzip function to

    Unzip $i.FullName