Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all articles
Browse latest Browse all 6937

Loops ForEach and For speed difference and results difference Questions

$
0
0

Hey all, 

Working with PowerShell and Outlook for a folder that's getting rather unruly. 

 

I created a script that used a foreach loop to delete all emails in a folder, When ever i run it though it only deletes half of the emails in the folder. but does so in a semi quick manner. 

when i change it to a for loop it deletes every email but does it a snails pace.. 

So my questions are: 

Why is the FOREACH only looping through half of the results (never seen do that before, is it a bug with outlook coms?). 

and

Why is the FOR loop sooo very slow

 

CODE: 

 

#Outlook Connection

$Outlook = New-Object -ComObject Outlook.Application

# Outlook folder to clean up and load into SQL

$EmailsInFolder = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").Folders.Item("__ SCOM Alerts").Items

## FOR Loop

FOR ( $i=($EmailsInFolder.count-1) ; $i -ge 0 ; $i-- )

    {

        $($EmailsInFolder)[$i].Delete()

        #write-host $i

    }

 

 

CODE@ FOREACH

 

#Outlook Connection

$Outlook = New-Object -ComObject Outlook.Application

# Outlook folder to clean up and load into SQL

$EmailsInFolder = $Outlook.Session.Folders.Item(1).Folders.Item("Inbox").Folders.Item("__ SCOM Alerts").Items

## FOREACH

FOREACH ($Email in $EmailsInFolder)

{

$Email.Delete()

}

 


Viewing all articles
Browse latest Browse all 6937

Trending Articles