PDQ.com mobilePDQ.com desktop
Support

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!

(CVE-2020-1472) 'ZeroLogon' Vulnerability

The Zerologon Vulnerability Allows Attackers To Completely Take Over Your Domain Controller Without Credentials.

PDQ.com
© 2020 PDQ.com Corporation

Products

  • PDQ Deploy
  • PDQ Inventory
  • PDQ Link
  • Enterprise SL
  • Pricing
  • Downloads
  • Licensing
  • Buy