Avatar of Rammy Charles
Rammy Charles
Flag for United States of America asked on

How to repeat PowerShell script

Im looking at a way to repeat the below script x number of times. The script does not successfully delete all of the outlook messages on first pass so I want to have it automatically run 4 or 5 times, then quit. How can I do this?

 $objOutlook = New-Object -Com Outlook.Application
  $colItems = $objOutlook.Session.GetDefaultFolder('OlFolderDeletedItems').Items

  $olddate = (Get-Date).AddMonths(-2).ToShortDateString()
  $filtered = $colItems.Restrict("[ReceivedTime] <= '$olddate'")
  $filtered |
    % { $_.Delete() }
PowershellOutlookWindows 7

Avatar of undefined
Last Comment
Qlemo

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
SubSun

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Rammy Charles

ASKER
Thanks. This is exactly what I was looking for.
Qlemo

Not exactly. You should only need repeat the filter and delete, if at all.
$objOutlook = New-Object -Com Outlook.Application
$colItems = $objOutlook.Session.GetDefaultFolder('OlFolderDeletedItems').Items

$olddate = (Get-Date).AddMonths(-2).ToShortDateString()
0..10| %{
  $filtered = $colItems.Restrict("[ReceivedTime] <= '$olddate'")
  $filtered |
    % { $_.Delete() } 
}

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck