简体   繁体   English

将一种文件添加到一个zip文件中,然后使用PowerShell进行清理

[英]Add files of one type to one zip file and clean up using PowerShell

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. 如何创建PowerShell脚本以获取所有.BAK类型的文件并将其添加到ZIP文件中(调用时我能否让我的PowerShell脚本使用一个参数来控制将容纳所有.bak文件的ZIP文件的名称?成功压缩后,删除.bak文件。

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. 我对PowerShell还是很陌生,目前我有脚本将每个.bak文件压缩为.zip文件,这是不好的。

$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: 如果您使用的是PowerShell v5,则可以使用Compress-Archive函数而不是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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM