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

set-CASMailbox parameters in detail

set-CASMailbox -Identity <MailboxIdParameter>

SAMPLES

Set-CASMailbox -Identity adam@contoso.com -OWAEnabled:$true -POPEnabled:$true

This example enables Exchange ActiveSync logging, blocks Outlook Anywhere, and specifies the Exchange ActiveSync mailbox policy for the user adam@contoso.com.

  • [-ActiveSyncAllowedDeviceIDs <MultiValuedProperty>]
  • [-ActiveSyncBlockedDeviceIDs <MultiValuedProperty>]
  • [-ActiveSyncDebugLogging <$true | $false>]
  • [-ActiveSyncEnabled <$true | $false>]
  • [-ActiveSyncMailboxPolicy <MailboxPolicyIdParameter>]
  • [-Confirm [<SwitchParameter>]] [-DisplayName <String>]
  • [-DomainController <Fqdn>] [-ECPEnabled <$true | $false>]
  • [-EmailAddresses <ProxyAddressCollection>]
  • [-EmwsEnabled <$true | $false>]
  • [-EwsAllowEntourage <$true | $false>]
  • [-EwsAllowList <MultiValuedProperty>]
  • [-EwsAllowMacOutlook <$true | $false>]
  • [-EwsAllowOutlook <$true | $false>]
  • [-EwsApplicationAccessPolicy <EnforceAllowList | EnforceBlockList>]
  • [-EwsBlockList <MultiValuedProperty>] [-EwsEnabled <$true | $false>]
  • [-HasActiveSyncDevicePartnership <$true | $false>]
  • [-IgnoreDefaultScope <SwitchParameter>]
  • [-ImapEnabled <$true | $false>]
  • [-ImapEnableExactRFC822Size <$true | $false>]
  • [-ImapMessagesRetrievalMimeFormat <TextOnly | HtmlOnly | HtmlAndTextAlternative | TextEnrichedOnly | TextEnrichedAndTextAlternative | BestBodyFormat | Tnef>]
  • [-ImapSuppressReadReceipt <$true | $false>] [-ImapUseProtocolDefaults <$true | $false>]
  • [-MAPIBlockOutlookNonCachedMode <$true | $false>]
  • [-MAPIBlockOutlookRpcHttp <$true | $false>]
  • [-MAPIBlockOutlookVersions <String>]
  • [-MAPIEnabled <$true | $false>] [-Name <String>]
  • [-OWAEnabled <$true | $false>]
  • [-OwaMailboxPolicy <MailboxPolicyIdParameter>]
  • [-PopEnabled <$true | $false>] [-PopEnableExactRFC822Size <$true | $false>]
  • [-PopMessagesRetrievalMimeFormat <TextOnly | HtmlOnly | HtmlAndTextAlternative | TextEnrichedOnly | TextEnrichedAndTextAlternative | BestBodyFormat | Tnef>]
  • [-PopSuppressReadReceipt <$true | $false>] [-PopUseProtocolDefaults <$true | $false>]
  • [-PrimarySmtpAddress <SmtpAddress>] [-SamAccountName <String>]
  • [-ShowGalAsDefaultView <$true | $false>]
  • [-WhatIf [<SwitchParameter>]