How can I create a PowerShell script to get all files of type .BAK and add them to a ZIP file (can I have my PowerShell script take a parameter when called to control the name of the ZIP file that will house all the .bak files? Deleting the .bak files once successfully zipped up.
The current directory is:
C:\SQLBackups +- a.bak +- b.bak `- c.bak
Goal is:
C:\SQLBackups `- v4.14.4_backups.zip
I'm pretty new to PowerShell, and I have currently the script zipping every .bak file into a .zip file which is no good.
$filePath = "C:\SQLBackups\"
$bak = Get-ChildItem -Recurse -Path $filePath |
Where-Object { $_.Extension -eq ".bak" }
if (-not (Test-Path "$env:C:\Program Files\7-Zip\7z.exe")) {
throw "$env:Program Files (x86)\7-Zip\7z.exe needed"
}
Set-Alias sz "$env:ProgramFiles\7-Zip\7z.exe"
foreach ($file in $bak) {
$name = $file.Name
$directory = $file.DirectoryName
$zipfile = $name.Replace(".bak", ".zip")
sz a -t7z "$directory\$zipfile" "$directory\$name"
}
The current output would be:
a.bak a.zip b.bak b.zip c.bak c.zip
If you're using PowerShell v5 then you can use the Compress-Archive
function instead of using 7zip:
$filePath = "C:\SQLBackups"
$ZipName = "v4.14.4_backups.zip"
$BakFiles = Get-ChildItem -Recurse -Path $filePath -Include *.bak
$BakFiles | Compress-Archive -DestinationPath "$filePath\$ZipName"
$BakFiles | Remove-Item -Force
You name the archive after each file you're processing in the loop, hence each file goes into its own archive. If you want to put all files into the same archive, define the archive name once outside the loop:
$zipfile = Join-Path $filePath 'v4.14.4_backups.zip'
foreach ($file in $bak) {
sz a -t7z $zipfile $file.FullName
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.