0

Is there any way to check if Outlook can successfully connect to Exchange from Powershell? I would like to schedule that script for logging purposes.

After some research, I managed to cook up the following:

$outlook = New-Object -ComObject Outlook.Application
Start-Sleep -s 5

$session = $outlook.session
$inbox = $session.GetDefaultFolder([Microsoft.Office.Interop.Outlook.olDefaultFolders]::olFolderInbox)

$date = Get-Date
If ($session.Offline) {
    $output = "Fail, mode $($session.ExchangeConnectionMode.ToString())"
} Else {
    $output = "Success"
}
"[$date] $output `n" | Out-File -Append "$HOME\ol_log.txt" -Encoding "UTF8"
$outlook.Quit()

This writes "Success" even if I pull the cable. A different way to check I found is

$validStates = "olCachedConnectedDrizzle", "olCachedConnectedDrizzle", "olCachedConnectedHeaders", "olOnline"
if ($validStates -contains $session.ExchangeConnectionMode.ToString()) {...}

...which always fails, since connection mode here is olCachedDisconnected for some reason. If I manually open Outlook, I can see the connection is OK. All of this is happening in an internal network, so no O365 and such.

PS: Please tell me if the question is more appropriate for superuser.com, I'll move it there if need be.

Atmaks
  • 101
  • 1

2 Answers2

0

I think “$session.ExchangeConnectionMode.ToString()” would return an OlExchangeConnectionMode constant that indicates the connection mode of the user's primary Exchange account. It would be like “800”, “300” or others.

You could try to use “500”, “600”, “700”, “800” as $validStates . Here is a reference. https://docs.microsoft.com/en-us/office/vba/api/outlook.olexchangeconnectionmode

Shaw
  • 339
  • 1
  • 4
  • Nope, I checked it with a live Powershell session, it is displayed correctly. I've seen the reference you mention. – Atmaks Apr 25 '19 at 08:38
  • I’m not very familiar with such script, maybe you could get support from some dev forums. – Shaw Apr 29 '19 at 08:53
0

Finally got it rught. Turns out adding another "Start-Sleep -s 5" after querying inbox solves the issue. It seems like the script was executing too fast for Outlook.

Atmaks
  • 101
  • 1