liveBook · Manning

ZipFile

As explained in Practical Automation with PowerShell: Effective scripting from the console to the cloud

System.IO.Compression.ZipFile is a .NET class that provides operations for reading and creating ZIP archives.

System.IO.Compression.ZipFile provides PowerShell access to ZIP archives through .NET. Load System.IO.Compression.FileSystem with Add-Type, then call the class directly using bracketed type names and static methods. section 2.1.6

Use OpenRead to inspect archive entries, then compare each expected file by name and size. Missing files generate nonterminating errors with Write-Error, allowing the remaining checks to continue. section 2.1.6

Listing 2.2 Deleting archived files
Function Remove-ArchivedFiles {
    [CmdletBinding()]
    [OutputType()]
    param(
    [Parameter(Mandatory = $true)]
    [string]$ZipFile,
 
    [Parameter(Mandatory = $true)]
    [object]$FilesToDelete,
 
    [Parameter(Mandatory = $false)]
    [switch]$WhatIf = $false
    )
    $AssemblyName = 'System.IO.Compression.FileSystem'               #1
    Add-Type -AssemblyName $AssemblyName | Out-Null
 
    $OpenZip = [System.IO.Compression.ZipFile]::OpenRead($ZipFile)
    $ZipFileEntries = $OpenZip.Entries                               #2
 
    foreach($file in $FilesToDelete){                                #3
        $check = $ZipFileEntries | Where-Object{ $_.Name -eq $file.Name -and
            $_.Length -eq $file.Length }
        if($null -ne $check){                                        #4
            $file | Remove-Item -Force -WhatIf:$WhatIf               #5
        }
        else {
            Write-Error "'$($file.Name)' was not find in '$($ZipFile)'"
        }
    }
}

A reusable Remove-ArchivedFiles function demonstrates assembly loading, read-only archive access, entry matching, and optional WhatIf-protected deletion. section 2.1.6

How Practical Automation with PowerShell: Effective scripting from the console to the cloud covers it

How deep it goes
Explains assembly loading, static OpenRead access, entry matching, and error behavior, but does not detail archive creation internals.
Examples
Demonstrates Remove-ArchivedFiles matching archive entries against files by name and size before deletion.
What it assumes
Assumes PowerShell familiarity while demonstrating how to load and call the required .NET namespace.
What you can do after
Apply ZipFile through PowerShell to inspect archive entries and safely automate validated file deletion.
How it connects
Connects .NET, PowerShell, ZIP archives, Add-Type, OpenRead, foreach, Write-Error, and WhatIf.

This explainer was generated by Manning's knowledge graph from the text of Practical Automation with PowerShell: Effective scripting from the console to the cloud. The section links point to the parts of the book it draws on.