Office365 via PowerShell in ASP.NET -> MicrosoftOnlineException

I have an ASP.NETapplication which uses PowerShell to connect to Office 365 to retrieve some details about user licenses.

The code itself works in many cases:

And where it doesn't work is of course the only place it really should work: The IIS on the target server.

I always get an Exception when calling the Connect-MsolService cmdlet. The problem is that the Exception doesn't tell me anything.

The Exception type is

Microsoft.Online.Administration.Automation.MicrosoftOnlineException

and the message is

Exception of type 'Microsoft.Online.Administration.Automation.MicrosoftOnlineException' was thrown

which is pretty useless.

The Office 365 user account I use in my code is always the same. The user account used to start the IIS is always the same, too (Local System).

I wrapped the PowerShell code execution in a class named PowerShellInvoker. Its code can be found here.

And here is the code that connects to Office 365:

var cred = new PSCredential(upn, password);
_psi = new PowerShellInvoker("MSOnline");
_psi.ExecuteCommand("Connect-MsolService", new { Credential = cred });

There is no Exception actually thrown, the error is found in the Error property of the pipeline. (See lines 50ff. of the PowerShellInvoker class.)

The server runs on Windows Server 2008 R2 Datacenter SP1 with IIS 7.5.

Řešení

On the target server, the app pool's advanced settings for my app had set Load User Profile to False. I changed it back to True (which should be default) and voilà, it works!

False was the default behavior until IIS 6.0.


viz: http://stackoverflow.com/questions/11968836/o365-via-powershell-in-asp-net-mvc-3-microsoftonlineexception-was-thrown