我有一个PowerShell脚本,我正在编写,我需要保留当月的每日备份,一年中的月末备份,并删除除此之外的任何内容。
$ThisYear = (Get-Date).year
$DailyLogs = (Get-Date).month
#Clean-Up Old Backup Files
Get-ChildItem 'D:\' | ForEach-Object {
if ( $_.LastWriteTime.Year -gt $ThisYear) {
Remove-Item
}
Elsif ( $_.LastWriteTime.Month -gt $ThisMonth -and $_.LastWriteTime.Date -ne ) {
Remove-Item
}
到目前为止,这应该删除任何不是当前年份的备份文件。我试图解决的问题是如何删除除当前月份之后每个月末的备份文件之外的每日备份。我被困在如何获得-ne到任何给定月份的最后一天。
编辑:
#Clean-Up Old Backup Files
Get-ChildItem 'D:\Server Backup\' | ForEach-Object {
if ( $_.LastWriteTime.Year -gt $ThisYear) {
Remove-Item
}
Elsif ( $_.LastWriteTime.Month -gt $ThisMonth -and $_.LastWriteTime.Date -ne [System.DateTime]::DaysInMonth($_.LastWriteTime.Year, $($_.LastWriteTime.Month))) {
Remove-Item
}
}
基于Lee的评论,这是我的想法。
替代30天滚动和月初:
$RollingYear = (Get-Date).AddDays(-365)
$Rolling30Days = (Get-Date).AddDays(-30)
if ( $_.LastWriteTime.AddDays(-365) -lt $RollingYear) {
Remove-Item
}
Elseif ( $_.LastWriteTime.AddDays(-30) -lt $Rolling30Days -and $_.LastWriteTime.Date -ne (Get-Date -Year $_.LastWriteTime.Year, -Month $_.LastWriteTime.Month -Day 1)) {
Remove-Item
}
我相信这就是你要找的东西:
param($Path)
$Now = (get-date)
$ThisYear = $Now.AddYears(-1).Year
#Clean-Up Old Backup Files
Get-ChildItem $path | ForEach-Object {
if ( $_.LastWriteTime.Year -lt $ThisYear)
{
write-output "-- would have deleted $($_.fullname) $($_.LastWriteTime.DateTime)"
}
Elseif ($_.LastWriteTime.Day -ne [System.DateTime]::DaysInMonth($_.LastWriteTime.Year, $($_.LastWriteTime.Month)))
{
write-output "would have deleted $($_.fullname) $($_.LastWriteTime.DateTime)"
}
else
{
Write-Output "saved $($_.FullName) $($_.LastWriteTime.DateTime)"
}
}
我假设你想从剧本运行那天起保持12个月。
我用它来测试你的脚本:
for ($i = 1; $i -lt 500; $i++)
{
new-item "$i.txt"
(Get-ChildItem "$i.txt").lastwritetime = (get-date).AddDays(-$i)
}
我注释掉了前两个写输出,这是我的结果:
saved C:\temp\temp\103.txt Friday, November 30, 2018 9:38:00 PM
saved C:\temp\temp\13.txt Thursday, February 28, 2019 9:37:59 PM
saved C:\temp\temp\133.txt Wednesday, October 31, 2018 9:38:00 PM
saved C:\temp\temp\164.txt Sunday, September 30, 2018 9:38:00 PM
saved C:\temp\temp\194.txt Friday, August 31, 2018 9:38:00 PM
saved C:\temp\temp\225.txt Tuesday, July 31, 2018 9:38:00 PM
saved C:\temp\temp\256.txt Saturday, June 30, 2018 9:38:00 PM
saved C:\temp\temp\286.txt Thursday, May 31, 2018 9:38:00 PM
saved C:\temp\temp\317.txt Monday, April 30, 2018 9:38:01 PM
saved C:\temp\temp\347.txt Saturday, March 31, 2018 9:38:01 PM
saved C:\temp\temp\378.txt Wednesday, February 28, 2018 9:38:01 PM
saved C:\temp\temp\406.txt Wednesday, January 31, 2018 9:38:01 PM
saved C:\temp\temp\41.txt Thursday, January 31, 2019 9:37:59 PM
saved C:\temp\temp\72.txt Monday, December 31, 2018 9:37:59 PM