The script below does the following - create a new email, open an excel file, copy content from it, paste into the new email and send it.
I have two PCs on which script was tested. The script was developed on PC1 using PowerShell 2.0 64 bit ISE. PC1- Windows 7 64 bit with SP1, Office 2010 32 bit and PowerShell 2.0.
PC2- Windows 7 64 bit with SP1, Office 2010 32 bit and PowerShell 3.0.
I have run the script on both machines using PowerShell ISE. The main difference between the two machines is the PowerShell version.
Add-type -assembly "Microsoft.Office.Interop.Outlook" | out-null
$olFolders = "Microsoft.Office.Interop.Outlook.olDefaultFolders" -as [type]
$outlook = new-object -comobject Outlook.Application
$namespace = $outlook.GetNameSpace("MAPI")
$InboxFolder = $namespace.getDefaultFolder($olFolders::olFolderInBox)
$InboxItems = $InboxFolder.items
$newmail = $outlook.CreateItem(0)
$newmail.Display()
$newmail.Recipients.Add("user@domain.com")
$newMail.Subject = "Report"
$excel = New-Object -comobject Excel.Application
$FilePath = "D:\Report.xlsx"
$ReportWorkBook = $excel.Workbooks.Open($FilePath)
$excel.Visible = $true
$ws = $ReportWorkBook.Worksheets.Item(1)
$SelectedRange = $ws.UsedRange
$SelectedRange.Copy()
# PasteExcelTable works on PC1 but Fails on PC2 consistently (with PowerShell 3.0)
#$newmail.HTMLBody +=$newmail.GetInspector.WordEditor.Range().PasteExcelTable($false,$false,$true)
# Paste() worked on both PCs
$newmail.GetInspector.WordEditor.Range().Paste()
$newMail.Send()
$excel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
Remove-Variable excel
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($outlook)
Remove-Variable outlook
One consistent problem is - the Excel.exe process started by powershell never exits after script has finished running. I have to kill the task manually via task manager. (I am planning to post a separate question to get a solution to this.)
The main problem however is the consistent crashing of Outlook 2010 but the point at which it crashes is inconsistent .
The script was run on PC1 (with PowerShell 2) via the ISE 5-6 times and each test generated an email. However a few mins after the last successful test run i got a "Not responding" dialog box in Outlook 2010 and it gave me the option to restart it. After restarting Outlook is froze again and then i had to kill the process and start it again.
On PC2 with PowerShell 3 (via the ISE) each time i ran the script Outlook froze. It seemed to always crash the paste operation. Using $newmail.GetInspector.WordEditor.Range().Paste()
worked on PC2. However a couple of minutes after the email was sent successfully, Outlook froze again.
As you can see - there is no consistency in when Outlook crashes/freezes...sometimes it is while pasting, sometimes when trying to send or save email and sometimes after sending an email!