Link to home
Start Free TrialLog in
Avatar of Rammy Charles
Rammy CharlesFlag 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() }
ASKER CERTIFIED SOLUTION
Avatar of SubSun
SubSun
Flag of India 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 Rammy Charles

ASKER

Thanks. This is exactly what I was looking for.
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