Avatar of Andrew Mellor
Andrew Mellor
 asked on

Use of Wild Cards in PS Script?

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 :-)
PowershellScripting Languages

Avatar of undefined
Last Comment
Andrew Mellor

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
ste5an

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Andrew Mellor

ASKER
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
Andrew Mellor

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

Regards

Andy
Andrew Mellor

ASKER
Perfect
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck