Excel 不接受来自 PowerShell 的数据

时间:2021-07-12 15:22:18

标签: excel powershell outlook

我正在使用 PowerShell 对我的 Outlook 电子邮件进行数据挖掘,然后将该数据导出到 Excel 工作表。我想获取每封电子邮件的主题、发件人姓名和接收时间。我可以从 Outlook 中获得所有三个,但是当我将数据导出到 excel 时,PowerShell 会针对发件人名称和接收时间抛出错误异常。有问题的代码部分是我的 foreach 语句:

$i = 0
foreach($item2 in $mail)
{

#$item2 | select subject // each of these displays the correct information in PowerShell
#$item2 | select senderName
#$item2 | select ReceivedTime

$item3 = $item2 | Select-Object -Property senderName // Copies senderName to a new variable
Write-Output $item3 // Successfully displays senderName

$Data.Cells.Item($i, 2) = $item2 // No issues, data is successfully export to excel
$Data.Cells.Item($i, 3) = $item3 // Throws exception when I try to export $item3
$i++;
}

抛出异常:

Exception from HRESULT: 0x800A03EC
At C:\Users\Tower\Documents\testingMail.ps1:45 char:5
+     $Data.Cells.Item($i, 3) = $item3
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
 
  

完整代码:

Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$Outlook = New-Object -comobject Outlook.Application
$namespace = $Outlook.GetNameSpace("MAPI")

$inbox = $namespace.GetDefaultFolder([Microsoft.Office.Interop.Outlook.OlDefaultFolders]::olFolderInbox)
$MyFolder1 = $namespace.Folders.Item('YOUREMAIL@EMAIL.COM').Folders.Item('Inbox')
$rules = $namespace.DefaultStore.GetRules()
$rule = $rules.create("My rule1: Receiving Notification",[Microsoft.Office.Interop.Outlook.OlRuleType]::olRuleRecieve) 


$mail = $namespace.Folders.Item(1).Folders.Item(2).Folders.Item(1).Items

$Path = 'C:\Users\Tower\Documents\mail.xlsx'

$excel = New-Object -ComObject excel.application
$excel.visible = $True
$workbook = $excel.Workbooks.Open($Path)
$i = 1
$workbook.Worksheets.Add()
$Data= $workbook.Worksheets.Item(1)

$i = 0
foreach($item2 in $mail)
{

#$item2 | select subject // each of these displays the correct information in PowerShell
#$item2 | select senderName
#$item2 | select ReceivedTime

$item3 = $item2 | Select-Object -Property senderName // Copies senderName to a new variable
Write-Output $item3 // Successfully displays senderName

$Data.Cells.Item($i, 2) = $item2 // No issues, data is successfully export to excel
$Data.Cells.Item($i, 3) = $item3 // Throws exception when I try to export $item3
$i++;
}

0 个答案:

没有答案