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 t开发者_如何学Goo have provisions for the multiple parameters that GetSharedDefaultFolder()
requires.
I have managed to get this working using the InvokeMember method of System.__ComObject. In order to pass multiple parameters to the method, simply enclose them in parentheses.
An example of the line of code is shown here:
PS C:> $usercontacts=[System.__ComObject].InvokeMember("GetSharedDefaultFolder" [System.Reflection.BindingFlags]::InvokeMethod,$null,$mapi,($user,10))
$user is the recipient object previously set up. $mapi is the MAPI namespace object (also set up previously).
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
Try replacing olFolderCalendar
with the number 9
.
COM objects need the actual values. They cannot convert clear text names to constant values.
精彩评论