I have a script in PowerShell that scans a directory of folders that are named with the following convention: yyyymmdd. It scans the directory and finds all the folders that are current and up to one week old, then copies them over to another directory. After it copies them over to the other directory, I would like to have it delete the folders in the new directory which are named the same way and that are older than 18 months old. Would there be an easy way to do this? I have pasted the script below.
$targetdirectory = "\\DPR320-W12-1600\PRTG"
$sourcedirectory = "C:\Users\Public\Documents\PRTG Traffic Grapher"
$todaysdate=get-date
$minusoneweek=$todaysdate.adddays(-7)
$minusdate=($minusoneweek.Month).tostring(),($minusoneweek.day).tostring(),($minusoneweek.year).tostring()
$todaysdatestring=($todaysdate.Month).tostring(),($todaysdate.day).tostring(),($todaysdate.year).tostring()
$oldfilename=$minusdate[0]+$minusdate[1]+$minusdate[2]+" backup"
$newfilename=$todaysdatestring[0]+$todaysdatestring[1]+$todaysdatestring[2]+" backup"
Get-ChildItem $sourcedirectory\config | Where-Object {
$_.PsIsContainer -and
$_.BaseName -match '\d{6}' -and
([DateTime]::ParseExact($_.BaseName, 'yyyyMMdd', $null) -gt (Get-Date).AddDays(-7))
} |Copy-Item -Recurse -Force -Destination $targetdirectory\$oldfilename\config
Copy-Item -Force $sourcedirectory\config.csv -Destination $targetdirectory\$oldfilename
Copy-Item -Force $sourcedirectory\config.prtg -Destination $targetdirectory\$oldfilename
rename-item $targetdirectory\$oldfilename $newfilename
Based on your discussion with FoxDeploy: This will loop through $YourDirectory and check if the name represents the date that's older than 18 months. Used this for my own cleanup, except I have names in dotted format.
$CleanupList = Get-ChildItem $YourDirectory
$Threshold = (get-date).AddMonths(-18)
foreach ($DirName in $CleanupList)
{
If (([datetime]::ParseExact($DirName.BaseName,'yyyyMMdd',$null)) -lt $Threshold)
{
Remove-Item $DirName.FullName -Force -Recurse
}
}