Compress-Archive, ForEach-Object and extra goodness

Was recently asked if zipping up a directory was something PowerShell could do.  Before version 5.0, you could do it using the ZipFile class ([System.IO.Compression.ZipFile]::CreateFromDirectory().  Thankfully, with PowerShell version 5+ we have the Compress-Archive cmdlet.

Below is an example that creates a few files in a directory and compresses.

<#  Compress-Archive example

    Demonstrating how to use the Compress-Archive cmdlet.

    We alse demonstrate a few other techinques:

    * getting content from a web site (Invoke-WebRequest)

    * use of the Foreach-Object

    * using the Measure-Object cmdlet to see the size of a directory

#>


# Create a folder and retrieve some data, happens once before the for-loop

$begin = {

    Set-Location -Path C:\TEMP

    # Create a new directory to hold our text files

    New-Item -Path . -Name ArchiveTest -ItemType Directory -Force | Out-Null

    # Go fetch the data!

    $url = ‘https://www.ams.usda.gov/mnreports/md_da800.txt’

    $value = (Invoke-WebRequest -Uri $url).content

}


# Create the files, this is the looping section

$process = {

    $name = “test$PSItem.txt”

    # Create a new file

    New-Item -Path .\ArchiveTest -Name $name -ItemType File -Force | Out-Null

    # add the content we snagged from above

    Add-Content “.\ArchiveTest\$name -Value $value

}


# Compress and compare, happens at the end of the looping

$end = {

    “Before compression: {0}” -f (Get-ChildItem .\ArchiveTest -Recurse | Measure-Object -property length -sum).sum

    Compress-Archive -Path .\ArchiveTest -DestinationPath .\ArchiveTest.zip -Force

    “After compression: {0}” -f (Get-ChildItem .\ArchiveTest.zip | Measure-Object -property length -sum).sum

}

# Magic happens

1..250 | ForEach-Object -Begin $begin -Process $process -End $end

Leave a Reply

Your email address will not be published. Required fields are marked *