25 June, 2013

PowerShell and C#: Can’t load MSOnline module

Crazy stuff, this PowerShell.

I was doing a C# program that needed to load in a PowerShell module with cmdlets intended for Office365. Even I had installed the x64 version of this module; it never showed up the proper place on the hard disk meaning my program failed to load it. Driven by a post on a forum somewhere on the WWW; I tried the following trick which actually worked to my surprise.

I’m running a x64 OS currently (Win8 Pro).

Copy the folder MSOnline from (1) –> (2) as seen here

1) C:\Windows\System32\WindowsPowerShell\v1.0\Modules\(MSOnline)

2) C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\(MSOnline)

After doing this trick, your x64 bit OS will happily load-in the MSOnline PS module into your runspace in your C# program.

    var iniSS = InitialSessionState.CreateDefault();
new[] { "MSOnline" });

var rs = RunspaceFactory.CreateRunspace(iniSS);

m_PowerShell =
m_PowerShell.Runspace = rs;

SecureString ss = m_PowerShellPwd.ConvertToSecureString();

var connectCmd = new Command("Connect-MsolService");
"Credential", new PSCredential (m_PowerShellUsr, ss));

//add to ps

var err = m_PowerShell.Streams.Error.ReadAll();


Anonymous said...

Thanks for this post. I spent hours trying to figure out why "get-modules -listavailable" worked differently when run from inside C# - producing a subset of what was available in the PS shell. Your trick worked and I can now access one of the missing modules that I needed.

Anonymous said...

Thanks man!! You saved me a lot of time.

Farid said...

i had all the right code all the right stuff but it still fails!
Followed your step of copying, it worked immediately...

Anonymous said...

Thanks for posting this. Ended up being the solution I needed!

ThisPseudonymIsTaken said...

Hi there,
I'm looking to create an app that can run powershell scripts for 365 administration. Can you help with a basic outline of what is needed to utilize your code to connect to a 365 portal as admin account so I can run powershell commands from the app to extend what you can achieve in the standard 365 portal?

Danish Butt said...
This comment has been removed by the author.
Danish Butt said...

I am still getting following message.

Could not load file or assembly 'file:///C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\MSOnline\Microsoft.Online.Administration.Automation.PSModule.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Damyan said...

Great! Thanks! This solution helped me.

iPhone/XCode - not all cases are equal!

This bit me! Having made some changes to an iPhone application (Obj-C); everything worked fine in the simulator. But, when deploying the s...