new to PS scripting so please bear with me.
I have the following folder structure - D:\Folder1, Folder2, Folder3.... Each parent folder has the same sub folder structure using yyyymmdd format (D:\Folder1\20221007). I would like to use PS to delete any folders older than 90 days in any of these sub-folders. We are always adding / removing parent folders. I was using the below script but its getting unmanageable as the parent folders are changing more frequently. I was thinking that I could list all the parent folders and pass them in and then loop through but not sure how best to do that. I would also like to write the full path of all the folders that were deleted, if possible.
$DaysAgo = (Get-Date).AddMonths(-3)
$Folders = (Get-ChildItem "D:\Folder1" | Where-Object {$_.PSIsContainer -Eq $True -And $_.Name -Match '^\d{8}'})
ForEach ($f In $Folders) {
$FolderDate = Get-Date -Year $f.Name.SubString(0,4) -Month $f.Name.SubString(4,2) -Day $f.Name.SubString(6,2)
If ($FolderDate -LT $DaysAgo) {
Remove-Item $f.FullName -Recurse
}
}
CodePudding user response:
here you go:
$DaysAgo = (Get-Date).AddMonths(-3)
#Specify the switch parameter "-Directory", so get-childitem will only return directories. Also you can filter on the creation date of the directory
$Folders = Get-ChildItem -Directory -Path "D:\Folder1" | Where-Object {$_.Name -Match '^\d{8}' -and $_.CreationTime -lt $DaysAgo}
#You can pass all paths to the parameter -path
$null = Remove-Item -Path $Folders.FullName -Confirm:$false -Force -recurse
CodePudding user response:
Give this a try:
$DaysAgo = (Get-Date).AddMonths(-3)
$Folders = Get-ChildItem -Directory "D:\Folder*\*"
ForEach ($f In $Folders) {
try {
$FolderDate = [Datetime]::ParseExact($f.Name, "yyyyMMdd", $null)
If ($FolderDate -lt $DaysAgo) {
Remove-Item $f.FullName -Recurse
}
} catch { }
}