# Get the files to zip
$FilesToZip = Get-ChildItem -Path $FolderPath -File
# Load the assembly to get the zip functionality
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null
# Set compression level
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
# Set Zip file pathc based on folder
$ZipPath = Join-Path $FolderPath "$(Split-Path $FolderPath -Leaf).zip"
# initialize the zip file
$Archive = [System.IO.Compression.ZipFile]::Open( $ZipPath, "Update" )
# add each file to the zip
Foreach($file in $FilesToZip){
$AddZip = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Archive, $file.FullName, $file.Name, $compressionLevel)
}
# release the zip
$Archive.Dispose()
Write-Output "The file '$ZipPath' has been created"
Creates a zip file and add every file from the specified directory into it. The zip file is named after the folder and will be placed inside of it.
PS C:\> $FolderPath = "C:\Scripts\Logs" >> $FilesToZip = Get-ChildItem -Path $FolderPath -File >> [Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" ) | Out-Null >> $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal >> $ZipPath = Join-Path $FolderPath "$(Split-Path $FolderPath -Leaf).zip" >> $Archive = [System.IO.Compression.ZipFile]::Open( $ZipPath, "Update" ) >> Foreach($file in $FilesToZip){ >> $AddZip = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Archive, $file.FullName, $file.Name, $compressionLevel) >> } >> $Archive.Dispose() >> Write-Output "The file '$ZipPath' has been created" The file 'C:\Scripts\Logs\Logs.zip' has been created