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!

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...