Office 365: Connect to Office Online 365 using Power Shell Script

I have a Windows Server 2008 R2 machine and it has Power Shell v1.0. I wanted to connect to the MS 365 online service using Power Shell with C #. I installed the Office 365 cmdlets and the Microsoft Online Services Login Assistant. (Link: http://onlinehelp.microsoft.com/en-us/office365-enterprises/hh124998.aspx#BKMK_install )

My script:

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

$credential = New-Object System.Management.Automation.PsCredential("xxxx@xxxx.onmicrosoft.com",$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 a problem running this script in a 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;
            try
            {
                runspace.Open();
                Pipeline pipeline = runspace.CreatePipeline();
                pipeline.Commands.AddScript(ss.toString());

                results = pipeline.Invoke();
            }
            finally
            {
                runspace.Close();
            }                
        }
    }

I get the following exception:

"Connect-Msolservice" , , script . , .

- ?

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

using (Runspace runspace = RunspaceFactory.CreateRunspace(iss))
{
// blah
}
+1

, , :

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

All Articles