Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting files older than 7 days, with exception for 1st day of the month

I need a scipt, that will delete a files older than 7 days, with exception for 1st day of the month.
Files created at 1st day of the month shouldnt be deleted. The part that i created for files older than 7 days works propperly, but i cant exclude the files from each 1st of month.

I tried to get the work done by following code, but the scipts is still deleting the files from 1st day of the month, even after adding the -notlike statement

Get-ChildItem C:\PSScripts\test -Recurse -Directory | 
Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-7) -and $_.CreationTime -notlike (GET-DATE -Format "MM/dd/yyyy" -Day 1) } |
Remove-Item -Force -Recurse

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to apply the same format to CreationTime as you do to Get-Date:

Get-ChildItem E:\Scripts\Powershell\TestFolder -Recurse -Directory | 
Where-Object {(Get-Date($_.CreationTime) -Format "MM/dd/yyyy") -notlike (GET-DATE -Format "MM/dd/yyyy" -Day 1) } 

That then returns only those that are not created on the 1st of the month

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading