PowerShell Command - To to ZIP file and folder

Article No :: KB00022


While working with Powershell scripts, sometimes we need to ZIP the big reports to send over the mail or to keep them in a centralised location. Below article will show how to achieve the same via Powershell.




###############################################################################

For Powershell versions 3 & 4

###############################################################################

Prior to Powershell Version 5, we are using the .Net 4.5 system compression assembly/classes to ZIP the files and folders. Below is the syntax for the same. In my few scripts, I have used this syntax only.


## Provide the ZIP Source and Destination Path


## Invoke the System assembly to ZIP the files. It will zip and keep the file into $ZIPDestination Folder.



###############################################################################

For Powershell versions 5 and above

###############################################################################

From PowerShell 5.0 onwards, we have the Compress-Archive and Expand-Archive built-in cmdlets to zip and unzip. We can still use the above .Net code as well. It is very well supported.


Please refer to the below examples for the syntax.


## Example 1 - It compresses files from a different location and creates a ZIP file. We can use the wildcard here, for multiple files with the same extension.


## Example 2 - It will compress Root directory and below sub-directories and files.


## Example 3 - It will compress all the files and sub-directories below the root "SourceLocation" folder. If we use "*.*", then it will only zip the files in "SourceLocation" folder.


Hope you guys like this article. In future, I will publish more PowerShell shortcodes required during scripting.





#PowershellScript #Microsoft #ZIPFileCode #CMDLets #PowerShellTweaks #EasyLearning