Older than X days Powershell script

Hello EE Community,

I'm in need of assistance in creating a PS script that does the following:

If I schedule a script to run on Fridays at 10AM, I need the script to go back 15 weeks from date, adds a day, so it'll be Saturday and delete any files older than 12am.

For example, if I run the script this Friday 11/23 at 10AM, the script will go back 15 weeks from date so it'll be Aug 10th adds a day so it'll be Saturday Aug 11th and deletes anything before 12am.


This is what I have so far:

$limit = (Get-Date).AddDays(-7 * 15)
$path = "\\SharePath"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.LastwriteTime -lt $limit } | Remove-Item -Force
Michael McGovernVP of Information TechnologyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

oBdACommented:
To get saturday at midnight, use the Date property and add a day.
And assuming you're not on the dinosaur PS 2.0, you can use -File instead of filtering in PowerShell, which is more efficient.
This is in test mode with the -WhatIf.
$limit = (Get-Date).Date.AddDays((-7 * 15) + 1)
$path = "\\SharePath"
# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -File -Force | Where-Object {$_.LastwriteTime -lt $limit} | Remove-Item -Force -WhatIf

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Michael McGovernVP of Information TechnologyAuthor Commented:
oBdA - your script worked like a charm! thank you!
Michael McGovernVP of Information TechnologyAuthor Commented:
oBdA - your script worked like a charm! thank you!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.