# Set the source and destination paths
$sourcePath = "C:\Path\To\Source\Folder"
$destinationPath = "C:\Path\To\Backup\Folder"
# Create the zip file name with the current date
$zipFileName = "backup_" + (Get-Date -Format "yyyy-MM-dd") + ".zip"
# Set the full destination path including the zip file name
$destinationPath = Join-Path -Path $destinationPath -ChildPath $zipFileName
# Create a new zip archive
$zipFile = [System.IO.Compression.ZipFile]::Open($destinationPath, [System.IO.Compression.ZipArchiveMode]::Create)
# Add the contents of the source folder to the zip archive
[System.IO.Directory]::GetFiles($sourcePath, "*", [System.IO.SearchOption]::AllDirectories) | ForEach-Object {
$entryName = $_.SubString($sourcePath.Length + 1)
$zipEntry = $zipFile.CreateEntry($entryName)
$zipStream = $zipEntry.Open()
$fileStream = [System.IO.File]::OpenRead($_)
$fileStream.CopyTo($zipStream)
$fileStream.Close()
$zipStream.Close()
}
# Close the zip archive
$zipFile.Dispose()
How it works:
- Set the
$sourcePathand$destinationPathvariables to the appropriate paths. - Create the
$zipFileNamevariable by concatenating the string "backup_", the current date formatted as "yyyy-MM-dd", and the file extension ".zip". This will create a zip file with the name "backup_yyyy-MM-dd.zip", e.g. "backup_2023-03-14.zip". - Use the
Join-Pathcmdlet to combine the$destinationPathand$zipFileNamevariables to create the full destination path including the zip file name. - Create a new zip archive using the
[System.IO.Compression.ZipFile]::Openmethod with the$destinationPathand[System.IO.Compression.ZipArchiveMode]::Createparameters. - Use the
[System.IO.Directory]::GetFilesmethod to get a list of all the files in the$sourcePathfolder and its subdirectories. - For each file, create an entry in the zip archive using the
$zipFile.CreateEntrymethod with the$entryNamevariable as the entry name. - Use the
$zipEntry.Openmethod to open a stream to the zip entry and the[System.IO.File]::OpenReadmethod to open a stream to the source file. - Use the
$fileStream.CopyTomethod to copy the contents of the source file to the zip entry stream. - Close the source file stream and the zip entry stream using the
$fileStream.Close()and$zipStream.Close()methods. - Close the zip archive using the
$zipFile.Dispose()method.