Я считаю, что это то, что вы ищете:
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