We help IT Professionals succeed at work.

Use of Wild Cards in PS Script?

112 Views
Last Modified: 2018-08-23
Dear Experts,

I currently use a reasonably simple PS script to delete any files older than 7 days.

These files originate from a number of different sources but ultimately reside in the same folder where I run my script.

They are prefixed with a client ID, followed by a sequential identifier...

eg:

CompanyA12345.rar
CompanyA12346.rar
CompanyB23456.rar
CompanyB23457.rar
CompanyC34567.rar
ComapnyC34568.rar

I now have a requirement to reduce the retention of some of the files down to 1 day. For example, files from Company A & B should retain files up to 7 days old, but Company C should only retain files up to 1 day old.

The script I currently use is shown below, and I was wondering if the best way to tackle this problem is to use wildcards. Do you agree? And if so, could you help me out with the syntax?

$limit = (Get-Date).AddDays(-7)
$path = "C:\ExtractedFiles"

# Delete files older than the $limit.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force

# Delete any empty directories left behind after deleting the old files.
Get-ChildItem -Path $path -Recurse -Force | Where-Object { $_.PSIsContainer -and (Get-ChildItem -Path $_.FullName -Recurse -Force | Where-Object { !$_.PSIsContainer }) -eq $null } | Remove-Item -Force -Recurse

Open in new window


I should add that I'm a simpleton when it comes to PS :-)
Comment
Watch Question

Senior Developer
CERTIFIED EXPERT
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Many thanks for this.

The files that are exported to my folder, do begin with a company identifier.

So in your script, am I correct in assuming that the script will remove all files older than 7 days, AND THEN, remove any files beginning with CompanyA or CompanyB that are older than 1 day?

Apologies for the questions.

Regards

Andy

Author

Commented:
I have just tested, and this works perfectly for me. Thanks so much.

Regards

Andy

Author

Commented:
Perfect
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.