- 1 year ago
Powershell - Sequential foreach loop zipping files
To sequentially zip files using PowerShell and a foreach loop, you can utilize the Compress-Archive
cmdlet. Here's an example:
powershell$sourcePath = "C:\path\to\source\folder" # Replace with the path to your source folder
$destinationPath = "C:\path\to\destination\folder" # Replace with the path to your destination folder
# Get the list of files in the source folder
$fileList = Get-ChildItem -Path $sourcePath -File
# Loop through each file and zip it
foreach ($file in $fileList) {
$zipFileName = "$($file.BaseName).zip"
$zipFilePath = Join-Path -Path $destinationPath -ChildPath $zipFileName
Compress-Archive -Path $file.FullName -DestinationPath $zipFilePath
}
In this example, the script sets the $sourcePath
variable to the path of the source folder containing the files you want to zip. The $destinationPath
variable is set to the path of the destination folder where the zip files will be created.
The Get-ChildItem
cmdlet retrieves a list of files in the source folder. The foreach
loop iterates through each file, and for each file, it creates a zip file with the same name in the destination folder using the Compress-Archive
cmdlet.
Make sure to replace the $sourcePath
and $destinationPath
variables with the actual paths to your source and destination folders.
By running this script, you will sequentially zip each file in the source folder using PowerShell.