Loading .msg file contents Using Powershell - Null Value error

Viewed 88

I am trying to access the metadata in a .msg file using Powershell (for example, get the sender address, subject line etc)

I have the following, simple code

Add-Type -assembly "Microsoft.Office.Interop.Outlook"

$outlook = New-Object -comObject Outlook.Application
$msg = $outlook.Session.OpenSharedItem("C:\Test\email.msg")

but I get the error

You cannot call a method on a null-valued expression. At line:4 char:1

If I run

$outlook

I get

Application        : 
Class              : 
Session            : 
Parent             : 
Assistant          : 
Name               : 
Version            : 
COMAddIns          : 
Explorers          : 
Inspectors         : 
LanguageSettings   : 
ProductCode        : 
AnswerWizard       : 
FeatureInstall     : 
Reminders          : 
DefaultProfileName : 
IsTrusted          : 
Assistance         : 
TimeZones          : 
PickerDialog       : 

all the properties appear to be null, including .Session, which explains why I get the null value error.

What have I done wrong in creating the $outlook object?

I have tried with both Outlook running and not running and the same happens.

I have Office 365 installed and I'm using Powershell 5.1.19041.1320

2 Answers

I managed to fix this issue by doing a "Quick Repair" of O365 in the programs and features dialog

On Windows 10 Pro and "Microsoft 365 Apps for Business," Quick Repair also worked for me 7/15/2022 when my similar script which creates a CVS export of selected Outlook Contacts stopped working, for the same reason, namely that the assignment to $outlook completed normally, but then $outlook had no parameter values, just as you show above, leading to the same null-valued expression error.

I had not run the script for a month or more, so can't say which or what kind of update broke it.

Here is an example of a valid value for $outlook, after repair (I set Product Code to all 0s in case that value identifies my license):

Application        : Microsoft.Office.Interop.Outlook.ApplicationClass
Class              : olApplication
Session            : Microsoft.Office.Interop.Outlook.NameSpaceClass
Parent             :
Assistant          : System.__ComObject
Name               : Outlook
Version            : 16.0.0.15330
COMAddIns          : System.__ComObject
Explorers          : {}
Inspectors         : {System.__ComObject, System.__ComObject, System.__ComObject, System.__ComObject...}
LanguageSettings   : System.__ComObject
ProductCode        : {00000000-0000-0000-0000-000000000000}
AnswerWizard       :
FeatureInstall     : msoFeatureInstallOnDemand
Reminders          : {$null, $null, $null, $null...}
DefaultProfileName : MS-2017-10
IsTrusted          : False
Assistance         : System.__ComObject
TimeZones          : {System.__ComObject, System.__ComObject, System.__ComObject, System.__ComObject...}
PickerDialog       : System.__ComObject
Related