Search code examples
compowershelloutlook

Powershell COM objects


I am attempting to get calendar items from a shared calendar via Powershell with the following code:

$outlook = new-object -ComObject Outlook.application
$session = $outlook.Session
$session.Logon("Outlook")
$namespace = $outlook.GetNamespace("MAPI")
$recipient = $namespace.CreateRecipient("John Smith")
$theirCalendar = $namespace.GetSharedDefaultFolder($recipient, "olFolderCalendar")

but I am getting a type mismatch error:

Cannot convert argument "0", with value: "System.__ComObject", for "GetSharedDefaultFolder" to type "Microsoft.Office.I nterop.Outlook.Recipient": "Cannot convert the "System.__ComObject" value of type "System.__ComObject#{00063045-0000-00 00-c000-000000000046}" to type "Microsoft.Office.Interop.Outlook.Recipient"." At line:1 char:34 + $namespace.GetSharedDefaultFolder <<<< ($recipient, "olFolderCalendar") + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

I've tried directly casting $recipient to a Microsoft.Office.Interop.Outlook.Recipient, which doesn't work, and I have also tried the invoke-method() procedure well documented here: http://www.mcleod.co.uk/scotty/powershell/COMinterop.htm

It seems like the latter should work, but it doesn't appear to have provisions for the multiple parameters that GetSharedDefaultFolder() requires.


Solution

  • Found a solution here: http://cjoprey.blog.com/2010/03/09/getting-another-users-outlook-folder/

    Add-Type -AssemblyName Microsoft.Office.Interop.Outlook
    
    $class = @”
    using Microsoft.Office.Interop.Outlook;public class MyOL
    {
        public MAPIFolder GetCalendar(string userName)
        {
            Application oOutlook = new Application();
            NameSpace oNs = oOutlook.GetNamespace("MAPI");
            Recipient oRep = oNs.CreateRecipient(userName);
            MAPIFolder calendar = oNs.GetSharedDefaultFolder(oRep, OlDefaultFolders.olFolderCalendar);
            return calendar;
        }
    }
    “@
    
    Add-Type $class -ReferencedAssemblies Microsoft.Office.Interop.Outlook