[PowerShell] How to zip or unzip files
Zip a file or multiple files
Open a PowerShell ISE and run the following code:
$SourcePath = "C:\PowerShellExercise\ZipOrUnzipFile\CustomerFiles"
$DestinationPath = "C:\PowerShellExercise\ZipOrUnzipFile\CustomerFiles"
Compress-Archive -Path $SourcePath -DestinationPath $DestinationPath
By default, I will use -Path variable, but if the source path contains special character likes C:\PowerShellExercise [ 1 ], then I will use -LiteralPath variable instead of -Path variable.
If there is a previous zipped file, add -Force or – Update parameter else it will throw an error message which said the file already exist.
Force parameter will overwrite the previous zipped file:
Compress-Archive -Path $SourcePath -DestinationPath $DestinationPath -Force
Update parameter will add the latest file into existing zipped file:
Compress-Archive -Path $SourcePath -DestinationPath $DestinationPath -Update
Multiple files in multiple zipped file
$SourcePath = "C:\PowerShellExercise\ZipOrUnzipFile\Files"
$DestinationPath = "C:\PowerShellExercise\ZipOrUnzipFile\Files"
$folderlist = Get-ChildItem -Path $SourcePath
Foreach ($folder in $folderlist)
{
Compress-Archive -path "$($folder.Fullname)" -DestinationPath "$($folder.Fullname).zip" -Force
}
Unzip a file or multiple files
$SourcePath = "C:\PowerShellExercise\ZipOrUnzipFile\Files.zip"
$DestinationPath = "C:\PowerShellExercise\ZipOrUnzipFile\Files"
Expand-Archive -LiteralPath $SourcePath -DestinationPath $DestinationPath
If there is a previous unzipped file, add -Force parameter to overwrite the previous one.