I have a directory, which consist of many sub-directories. Ex: "\IP\Share\Directory\Machine\Year\Month\Date\Image_ID"
The problem is that this directory stores images and I need to delete any images stored that are older than 730 Days. The issue is that there are hundreds of images on the "Image_ID" folder. Some times you can have up to 100 "Image_ID" folders created as well. I need to make a PowerShell script that will search for the directory create date, sort, and remove the directory closet to the "IP address" that was created older than 730 Days (Not the images/files because this process can take a whole day).
This is a daily task and I need to minimize the duration of the task. So I figured searching for the directory date, instead of the file date.
This is the script that I am using, which works for me. But its taking extremely long to complete, it runs the same delete line multiple times simply to delete sub-directories folders:
Param (
[string]$Source = "\IP\Share\Directory\Machine\Year\Month\Date\Image ID",
[string]$Days = "730"
)
$Folder = Get-ChildItem $Source -Recurse | Where-Object { !$_.PSIsContainer -and $_.LastWriteTime -le (get-date).adddays(-$($Days)) }
$Folder | Remove-Item -Force
$Folder = Get-ChildItem $source -Recurse -Force | Where {$_.PSIsContainer} | Sort-Object FullName -Descending | Where {!(Get-ChildItem $_.FullName -Force)}
$Folder | Remove-Item -Force
$Folder = Get-ChildItem $source -Recurse -Force | Where {$_.PSIsContainer} | Sort-Object FullName -Descending | Where {!(Get-ChildItem $_.FullName -Force)}
$Folder | Remove-Item -Force
$Folder = Get-ChildItem $source -Recurse -Force | Where {$_.PSIsContainer} | Sort-Object FullName -Descending | Where {!(Get-ChildItem $_.FullName -Force)}
$Folder | Remove-Item -Force
$Folder = Get-ChildItem $source -Recurse -Force | Where {$_.PSIsContainer} | Sort-Object FullName -Descending | Where {!(Get-ChildItem $_.FullName -Force)}
$Folder | Remove-Item -Force
stop-process -Id $PID
}
If I didn't explain something correctly I will try and clarify. I am new to PowerShell and this script was a combination of multiple ones that I made work.