Older than X days Powershell script

Michael McGovern
Michael McGovern used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
Commented:
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

Michael McGovernVP of Information Technology

Author

Commented:
oBdA - your script worked like a charm! thank you!
Michael McGovernVP of Information Technology
Commented:
oBdA - your script worked like a charm! thank you!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial