如何用Powershell定期压缩文件并删除

本篇将介绍如何使用Powershell定期压缩文件并删除。

要想执行本操作,首先要确定计算机已经安装了软件7zip。

以下代码仅仅删除7天以内文件。

具体Powershell代码如下:

Function Zip

{
Param
(
[string]$zipFile
,
[string[]]$toBeZipped
)
$CurDir = Get-Location
Set-Location “C:Program Files7-zip”
.7z.exe A -tzip $zipFile $toBeZipped | out-null
Set-Location $CurDir
}
$files1 = (Get-ChildItem D:TestlocationLogs*.* )

If((Test-Path D:TestlocationShare$(get-date -f yyyy-MM-dd).zip) -and (!$Files1))
{
write-host “No file to delete.”
}
else
{
$files = (Get-ChildItem D:TestlocationLogs*.* | Where-Object {$_.LastWriteTime -gt ((Get-date).adddays(-7))})
Zip D:TestlocationShare$(get-date -f yyyy-MM-dd).zip $Files
Remove-Item $files
}

代码将实现在固定文件夹压缩文件,压缩文件名为当天日期,如果没有文件,则返回没有文件需要删除。

将此代码保存成ps1文件,然后建立task scheduler要求每天运行一次。