0

I found a piece of code here that almost does what I need, which is extract just one folder from an archived file.

The only issue I have is that the archive name changes month on month, therefore I wanted to use a wildcard. Once a wildcard is specified (* in $zipfile), the script does not work for me.

I would be grateful for any suggestions.

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null

$zipfile = 'C:\ALL\Debtor*.zip'
$folder  = 'tmp\st\sd'
$dst     = 'C:\ALL\ZipOutput'

[IO.Compression.ZipFile]::OpenRead($zipfile).Entries | ? {
  $_.FullName -like "$($folder -replace '\\','/')/*.*"
} | % {
 $file   = Join-Path $dst $_.FullName
 $parent = Split-Path -Parent $file
 if (-not (Test-Path -LiteralPath $parent)) {
  New-Item -Path $parent -Type Directory | Out-Null
}
[IO.Compression.ZipFileExtensions]::ExtractToFile($_, $file, $true)
byuli
  • 55
  • 2
  • 12

1 Answers1

1

Try this out for size. Just use Get-ChildItem to locate the zip file in your ALL directory.

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null

    $zipfile = Get-ChildItem -Path C:\ALL\ -Filter *.zip | Where-Object {$_.Name -like "Debtor*"} | Select-Object -ExpandProperty FullName
    $folder  = 'tmp\st\sd\'
    $dst     = 'C:\ALL\ZipOutput'

    [IO.Compression.ZipFile]::OpenRead($zipfile).Entries | Where-Object {
        $_.FullName -like "$($folder -replace '\\','/')/*.*"
    } | ForEach-Object {
        $file   = Join-Path $dst $_.FullName
        $parent = Split-Path -Parent $file

        if(-not (Test-Path -LiteralPath $parent)) {
            New-Item -Path $parent -Type Directory | Out-Null
        }
        [IO.Compression.ZipFileExtensions]::ExtractToFile($_, $file, $true)
    }

I am also assuming that the archive name changes but there are not multiple archives with that name. If there are you will need to wrap everything in a Foreach($zip in $zipfile){ ... }

SysEngineer
  • 354
  • 1
  • 7
  • I get this error: `Exception calling "OpenRead" with "1" argument(s): "Path cannot be null. Parameter name: path" At line:7 char:5 + [IO.Compression.ZipFile]::OpenRead($zipfile).Entries | Where-Obje ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullException` – byuli Oct 08 '19 at 08:53
  • 1
    @user8449681 I just fixed the code. Please try it again.. I added -ExpandProperty Fullname. Previously to access the value you would have had to use $zipfile.fullname – SysEngineer Oct 08 '19 at 17:11
  • It works now, thank you very much!! The only other thing I did was deleted the last \ from the `$folder` value. – byuli Oct 09 '19 at 14:10