Skip to main content
PDQ.com mobilePDQ.com desktop
Support
Try Now

How to zip up files using .NET and Add-Type

Kris PowellKris Powell
·

I recently came across a need to zip up some files prior to copying them over the network. Normally, I’d simply use another tool such as WinZip or 7zip, but I thought I’d like to see how PowerShell could handle it.

There are many tools out there to help you with this (7zip cli, PowerShell community extensions, etc). They’re not included with Powershell, so I decided to try and make use of the tools we have at hand.

I decided to go with a quick way to zip up files by leveraging .NET and using the cmdlet Add-Type

Zipping files with PowerShell

Note: This requires .NET 4.5 and Powershell 3+

This example script is pretty straightforward and simple. It makes use of the System.IO.Compression.Zipfile class that was included with .NET 4.5. We make use of the PowerShell cmdlet Add-Type to add a Microsoft .NET Framework type to the PowerShell session. This allows to leverage .NET in our PowerShell scripts.

    = 
 = 
     =   

 -DestinationFileName  `
    -SourceDirectory  `
    -CompressionLevel  ` 
    -IncludeParentDir 

 Zip-Directory {
    (
      [(=)],
      [(=)],
      [(=)] = ,
      [(=)]
    )
     -AssemblyName System.IO.Compression.FileSystem
        =   
    CreateFromDirectory(, , , )
}


Did you know that PDQ Deploy has a PowerShell step you can use to deploy your scripts?


This blog post is part of a series on PowerShell:

Ready to put the PowerShell Scanner through its paces?

Take our 14-day Free Trial. Feel the power of the PowerShell scanner.
Start a Trial

Don't miss the next post!

Windows 11 First Look

Microsoft is gearing up for the release of Windows 11. Are you ready for it? Here's everything you need to know about Microsoft's newest operating system.

windows11
PDQ.com
© 2021 PDQ.com Corporation
Products
  • PDQ Deploy ®
  • PDQ Inventory ®
  • Pricing
  • Downloads
  • Licensing
  • Buy