0

the script below reads my outlook emails but how do I access the output. I'm new too Powershell and I'm still getting used to certain things. I just want to get the body of 10 unread outlook emails and store them in an Array called $Body.

$olFolderInbox = 6
$outlook = new-object -com outlook.application;
$ns = $outlook.GetNameSpace("MAPI");
$inbox = $ns.GetDefaultFolder($olFolderInbox)

#checks 10 newest messages
$inbox.items | select -first 10 | foreach {
if($_.unread -eq $True) {
$mBody = $_.body

#Splits the line before any previous replies are loaded
$mBodySplit = $mBody -split "From:"

#Assigns only the first message in the chain
$mBodyLeft = $mbodySplit[0]

#build a string using the –f operator
$q = "From: " + $_.SenderName + ("`n") + " Message: " + $mBodyLeft

#create the COM object and invoke the Speak() method 
(New-Object -ComObject SAPI.SPVoice).Speak($q) | Out-Null
} 
}
Ragnar
  • 1,442
  • 3
  • 16
  • 27

3 Answers3

1

define $body = @(); before your loop

Then just use += to add the elements

rerun
  • 25,014
  • 6
  • 48
  • 78
1

This may not be a factor here, since you're looping through only ten elements, but using += to add elements to an array is very slow.

Another approach would be to output each element within the loop, and assign the results of the loop to $body. Here's a simplified example, assuming that you want $_.body:

$body = $inbox.items | select -first 10 | foreach {
  if($_.unread -eq $True) {
    $_.body
  }
}

This works because anything that is output during the loop will be assigned to $body. And it can be much faster than using +=. You can verify this for yourself. Compare the two methods of creating an array with 10,000 elements:

Measure-Command {
  $arr = @()
  1..10000 | % { 
    $arr += $_ 
  }
}

On my system, this takes just over 14 seconds.

Measure-Command {
  $arr = 1..10000 | % { 
    $_
  }
}

On my system, this takes 0.97 seconds, which makes it over 14 times faster. Again, probably not a factor if you are just looping through 10 items, but something to keep in mind if you ever need to create larger arrays.

KevinD
  • 3,023
  • 2
  • 22
  • 26
  • I do plan on looping through a lot more messages and this really helps. Thanks for the help. now it does 500 messages way faster than the previous code – Ragnar Jan 02 '14 at 19:13
1

Here's another way:

$body = $inbox.Items.Restrict('[Unread]=true') | Select-Object -First 10 -ExpandProperty Body
Shay Levy
  • 121,444
  • 32
  • 184
  • 206