Link to home
Start Free TrialLog in
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 :-)
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Andrew Mellor
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
I have just tested, and this works perfectly for me. Thanks so much.

Regards

Andy
Perfect