InfiniTec - Henning Krauses Blog

Don't adjust your mind - it's reality that is malfunctioning

Exchange Managed API autodiscover with Powershell

Powershell is a great tool to automate all sorts of things – including fiddling around with your Exchange mailbox. And the Autodiscover makes it really easy to connect to it – especially if you’re on Office 365 and don’t even know your CAS server.

So first, we need to load the EWS Managed API dll into the current runspace:

[Reflection.Assembly]::LoadFrom("C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll")

Then, create an ExchangeService instance and set its credentials:

$service =  New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.Credentials = New-Object System.Net.NetworkCredential("", "password", "domain");

Now we are ready to use AutoDiscover. But depending on your infrastructure, AutoDiscover might need to follow some redirections before it has discovered your CAS Server. Like in this case:


Exception calling "AutodiscoverUrl" with "1" argument(s): "Autodiscover blocked a potentially insecure redirection to To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload."
At line:1 char:25
+ $service.AutodiscoverUrl <<<< ("");
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

This happens because the AutoDiscover process looks at and instead of an A record pointing to the AutoDiscover service, it finds a CNAME redirecting it to Because this might pose a security risk, the AutoDiscoverUrl method aborts  the discovery process and throws the Exception displayed above. The solution is also outlined: Instead of calling the method AutoDiscoverUrl(mailAddress) call the overload which expects a delegate as a second paramter. This delegate has a string as input and returns the $true if the discovery process should follow the redirection; false otherwise.

How can this overload be used with PowerShell? The answer is a ScriptBlock. If you simply want to allow the discovery process to follow all redirects, simply call it this way:

$service.AutodiscoverUrl("", {$true})

But if you want to verify the discovery process is redirected to the correct url, use this version:

$TestUrlCallback = {
 param ([string] $url)
 if ($url -eq "") {$true} else {$false}

$service.AutodiscoverUrl("", $TestUrlCallback)

You can embed whatever checks you need to verify the given url in the third line of the $TestUrlCallback method.

Posted by Henning Krause on Friday, July 22, 2011 5:30 PM, last modified on Sunday, July 24, 2011 1:22 AM
Permalink | Post RSSRSS comment feed