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();
iniSS.ImportPSModule(
new[] { "MSOnline" });

var rs = RunspaceFactory.CreateRunspace(iniSS);
rs.Open();

m_PowerShell =
PowerShell.Create();
m_PowerShell.Runspace = rs;

//credentials
SecureString ss = m_PowerShellPwd.ConvertToSecureString();

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

//add to ps
m_PowerShell.Commands.Clear();
m_PowerShell.Streams.Error.Clear();
m_PowerShell.Commands.AddCommand(connectCmd);

//connect
m_PowerShell.Invoke();
var err = m_PowerShell.Streams.Error.ReadAll();

4 comments:

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...

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

Anonymous said...

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