Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1447
  • Last Modified:

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() }
0
GR JN
Asked:
GR JN
1 Solution
 
SubsunCommented:
Simple method is to use a foreach loop to repeat the code..
0..10| %{ <Your code to repeat>}

Open in new window

Example to repeat the code ten times..
0..10| %{
$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() } 
}

Open in new window

0
 
GR JNAuthor Commented:
Thanks. This is exactly what I was looking for.
0
 
QlemoC++ DeveloperCommented:
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

0

Featured Post

Evaluating UTMs? Here's what you need to know!

Evaluating a UTM appliance and vendor can prove to be an overwhelming exercise.  How can you make sure that you're getting the security that your organization needs without breaking the bank? Check out our UTM Buyer's Guide for more information on what you should be looking for!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now