# 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
$sourcePath
and$destinationPath
variables to the appropriate paths. - Create the
$zipFileName
variable 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-Path
cmdlet to combine the$destinationPath
and$zipFileName
variables to create the full destination path including the zip file name. - Create a new zip archive using the
[System.IO.Compression.ZipFile]::Open
method with the$destinationPath
and[System.IO.Compression.ZipArchiveMode]::Create
parameters. - Use the
[System.IO.Directory]::GetFiles
method to get a list of all the files in the$sourcePath
folder and its subdirectories. - For each file, create an entry in the zip archive using the
$zipFile.CreateEntry
method with the$entryName
variable as the entry name. - Use the
$zipEntry.Open
method to open a stream to the zip entry and the[System.IO.File]::OpenRead
method to open a stream to the source file. - Use the
$fileStream.CopyTo
method 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.