Office 365: Connecting to Office Online 365 service using Power Shell Script issue

I have Windows Server 2008 R2 machine and it has Power Shell v1.0. I wanted to connect to MS 365 online service using Power Shell with C#. I have installed Office 365 cmdlets and Microsoft Online Services Sign-In Assistant. ( Ref: )

My script is:

$password = ConvertTo-SecureString "xxxxx" -AsPlainText –Force

$credential = New-Object System.Management.Automation.PsCredential("",$password)

$cred = Get-Credential -cred $credential

Import-Module MSOnline

Connect-Msolservice -cred $cred

I can successfully run this script in the Power Shell Command window. But I have problem running this script in c# application.

Here is my c# code:

  public void RunScript()
        StringBuilder ss = new StringBuilder();
        ss.AppendLine("$password = ConvertTo-SecureString \"" + pwd + "\" -AsPlainText –Force");
        ss.AppendLine("$credential = New-Object  System.Management.Automation.PsCredential(\"" + userName + "\",$password)");
        ss.AppendLine("$cred = Get-Credential -cred $credential");
        ss.AppendLine("Import-Module MSOnline");
        ss.AppendLine("Connect-Msolservice -cred $cred");

        using (Runspace runspace = RunspaceFactory.CreateRunspace())
            Collection<PSObject> results = null;
                Pipeline pipeline = runspace.CreatePipeline();

                results = pipeline.Invoke();

I get the following exception:

The term 'Connect-Msolservice' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Is there anything missing?



InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[] { "MSOnline" });

using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
// blah

Please make sure you have installed following things:

 1. SharePoint Online Management Shell
 2. Microsoft Online Services Sign-In Assistant version 7.0 or greater version
 3. Windows Azure Active Directory Module

Need Your Help

Run shell command in PHP from MAMP

php macos bash shell mamp

I have installed MAMP on my OSX and tried to run a shell command from my php file but it seems I can't access the terminal or the command is not being sent to terminal.

Interchanging/Swapping values between mysql fields

php mysql insert-update

So, after creating the field, the code and what else was needed to retrieve news order as mentioned here: Planning news ordering system