I have a primary folder c:\Directory under that is a %username% directory and under that is a Downloads directory with multiple directories in that folder. I need to create a script that will delete files older than 7 days from the Downloads directory of every user in the in the primary C:\directory%username%\Downloads … and logs the files that have been downloaded.
I have tried Get-ChildItem but that will only get me down one level from the c:\directory. I need to go all the way down to the Downloads directory in every users folder to do the delete.
[quote quote=203024]I have tried Get-ChildItem but that will only get me down one level from the c:\directory. I need to go all the way down to the Downloads directory in every users folder to do the delete.
[/quote]
# This still isn't tested, please test before using. It should meet all of your requirements.
$dateFilter = (Get-Date).AddDays(-7)
$userDownloadFolders = Get-ChildItem -Path C:\Users\ -Recurse -Directory -ErrorAction SilentlyContinue | ? {$_.Name -eq 'Downloads'}
$filesToRemove = @()
foreach ($userDownloadFolder in $userDownloadFolders )
{
$filesToRemove += Get-ChildItem -Path $userDownloadFolder.FullName -File -Recurse | ? {$_.LastWriteTime -lt $dateFilter}
}
$filesToRemove | % {$null = Remove-Item -Path $_.FullName -Force}