Run Exchange Online PowerShell Commands with C#

Instead of running PowerShell Commands within the Console, in some scenarios, it’s important to automate this procedure and give users the ability to manage Exchange Online. In this sample I’m creating a mailbox. I’m explaining all steps in code.

I Suggest to Run this sample first in a Console Application

image

Leave a message if you have any issues

using System.Collections.Generic;
using System.Management.Automation.Runspaces;
using System.Management.Automation;

// Set credentials to make a remote connection to Outlook Live
string userName = admin@contoso.com;

string password = "password";

SecureString secureString = new SecureString();
foreach (char c in password) secureString.AppendChar(c);
secureString.MakeReadOnly();

PSCredential credential = new PSCredential(userName, secureString);

// Set the connection Info
WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new

   
Uri("https://ps.outlook.com/powershell/"),
        "http://schemas.microsoft.com/powershell/Microsoft.Exchange"
, credential) 

     { AuthenticationMechanism = AuthenticationMechanism.Basic };

// create a runspace on a remote path
// the returned instance must be of type RemoteRunspace

Runspace runspace = RunspaceFactory.CreateRunspace();
PowerShell powershell = PowerShell.Create();
PSCommand command = new PSCommand();
command.AddCommand("New-PSSession");
command.AddParameter("ConfigurationName", "Microsoft.Exchange");
command.AddParameter("ConnectionUri", new Uri("https://ps.outlook.com/powershell/"));
command.AddParameter("Credential", credential);
command.AddParameter("Authentication", "Basic");

//-AllowRedirection
powershell.Commands = command;

// open the remote runspace
runspace.Open();

// associate the runspace with powershell
powershell.Runspace = runspace;

// invoke the powershell to obtain the results
Collection<PSSession> result = powershell.Invoke<PSSession>();

foreach (ErrorRecord current in powershell.Streams.Error)
   
Console.WriteLine(String.Format("The following Error happen when opening the remote Runspace: {0} | InnerException: {1}", 

     current.Exception, current.Exception.InnerException));
Console.ReadLine();
if (result.Count != 1)
   
throw new Exception("Unexpected number of Remote Runspace connections returned.");
// Set the runspace as a local variable on the runspace
powershell = PowerShell.Create();

command = new PSCommand();
command.AddCommand("Set-Variable");
command.AddParameter("Name", "ra");
command.AddParameter("Value", result[0]);
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();

powershell = PowerShell.Create();
command = new PSCommand();
const string CreateMailBoxScript = "new-mailbox -Name:'{0}’ -Password:(ConvertTo-SecureString {1}  -AsPlainText -Force) -WindowsLiveID:{2} -FirstName:{3} -LastName:{4} -DisplayName:'{5}’";
command.AddScript(string.Format(CreateMailBoxScript, "Joao", "password", jlivio@contoso.com, "Joao", "Livio", "Joao Livio"));
powershell.Commands = command;
powershell.Runspace = runspace;
powershell.Invoke();

// dispose the runspace and enable garbage collection
runspace.Dispose();

runspace = null;
// Finally dispose the powershell and set all variables to null to free
// up any resources.
powershell.Dispose();

powershell = null;

Advertisements

17 thoughts on “Run Exchange Online PowerShell Commands with C#

  1. Hello,
    I got compile error from following line….

    using System.Management.Automation.Runspaces;
    using System.Management.Automation;

    I can’t add reference to these.. Can you help?

    • Thanks for your reply. When I run the code I have got the following Exception. Can you please look at it & help me to solve this?…

      System.Management.Automation.Remoting.PSRemotingTransportException:
      Connecting to remote server failed with the following error message : The WinRM client cannot process the request. Unencrypted traffic is currently disabled in the client configuration. Change the client configuration and try the request again. For more information, see the about_Remote_Troubleshooting Help topic.

  2. Hello,
    Thanks for your reply. I have set the options as suggested in second link, But when I tried again I got new errors. Here is the error in detail.

    System.Management.Automation.Remoting.PSRemotingTransportException:
    Connecting to remote server failed with the following error message : The WinRM client cannot process the request. The authentication mechanism requested by the client is not supported by the server or unencrypted traffic is disabled in the service configuration. Verify the unencrypted traffic setting in the service configuration or specify one of the authentication mechanisms supported by the server. To use Kerberos, specify the computer name as the remote destination. Also verify that the client computer and the destination computer are joined to a domain. To use Basic, specify the computer name as the remote destination, specify Basic authentication and provide user name and password. Possible authentication mechanisms reported by server: For more information, see the about_Remote_Troubleshooting Help topic.

    If you could help me further , that would be great.

    Regards
    Sebastian

  3. Hi, Thanks for your help. I have posted in that forum & no yield yet. Is it possible to have a GOTO/Team viewer session to check the configurations in my machine? Thanks once again.

  4. Hi,
    Basic authentication was disabled in power-shell virtual directory, I have tried to execute this code after enabling basic authentication and now I have got a new error as follows

    The term ‘new-mailbox’ 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.

    Can you help me on this?
    Thanks for your support

    • Try to change the local ExecutionPolicy to “remotesigned”, for this open the powershell console on your machine executing the code, and type “Set-ExecutionPolicy remotesigned”

  5. Hi,

    When I try to get mail box data, using get-mailbox command, It threw another error.

    Active Directory operation failed on WIN-010LMRATJ8N.mjsindia.com. The supplied credential for ‘MJSINDIA\123’ on Bind operation is invalid. Error Code: 0x31.

    Regards
    Sebastian

  6. Hello Sir,
    I want to set email auto forwarding(journaling) activate and deactivate for a some period via this code…
    Please provide me code sir……
    thanks
    Balindra

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s