0

下面的脚本会读取我的 Outlook 电子邮件,但如何访问输出。我也是 Powershell 新手,我还在习惯某些事情。我只想获取 10 封未读 Outlook 电子邮件的正文并将它们存储在一个名为 $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
} 
}
4

3 回答 3

1

这可能不是一个因素,因为您只循环了十个元素,但是使用 += 向数组添加元素非常慢。

另一种方法是输出循环中的每个元素,并将循环的结果分配给 $body。这是一个简化的示例,假设您需要 $_.body:

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

这是可行的,因为在循环期间输出的任何内容都将分配给 $body。它可以比使用 += 快得多您可以自己验证这一点。比较创建具有 10,000 个元素的数组的两种方法:

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

在我的系统上,这只需要 14 秒多一点。

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

在我的系统上,这需要 0.97 秒,这使它快了 14 倍以上。同样,如果您只是循环遍历 10 个项目,这可能不是一个因素,但如果您需要创建更大的数组,请记住一些事情。

于 2013-12-31T21:59:00.447 回答
1

这是另一种方式:

$body = $inbox.Items.Restrict('[Unread]=true') | Select-Object -First 10 -ExpandProperty Body
于 2014-01-01T09:04:19.940 回答
1

$body = @();在你的循环之前定义

然后只需使用+=添加元素

于 2013-12-31T20:06:06.153 回答