Delete files from Sub-Folders of users older than x Days

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.

 

 

What have you tried? Have you looked at Get-ChildItem?

$dateFilter = (Get-Date).AddDays(-7)

$filesToRemove = Get-ChildItem -Path 'SomeUserDirectory' -File -Recurse | Where-Object {$_.LastWriteTime -lt $dateFilter }

$filesToRemove | Foreach-Object {$null = Remove-Item -Path $_.FullName -Force}

This isn’t tested. Test it.

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}

Could you please format your code as code using the code tag button (“PRE”)? Thanks.

You may re-read the very first pinned post on top of the list of this forum: Read Me Before Posting! You’ll be Glad You Did!