Question

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
} 
}
Était-ce utile?

La solution

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.

Autres conseils

define $body = @(); before your loop

Then just use += to add the elements

Here's another way:

$body = $inbox.Items.Restrict('[Unread]=true') | Select-Object -First 10 -ExpandProperty Body
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top