I'm working on a project where I need to create a security group in Azure AD and assign specific Exchange roles to this group using C#. I want to avoid using PowerShell commands for this task. Here is the command I normally use in PowerShell:
New-RoleGroup -Name "mailbox-import-export" -Description "import pst" -Roles "Mailbox Import Export","Mail Recipients" -ManagedBy "admin@mail.com" -Members "admin@mail.com"
So far, I have been able to create the group and add members using the Microsoft Graph .NET SDK by referring this document
The problem I'm facing is how to programmatically assign the specific Exchange roles ("Mailbox Import Export" and "Mail Recipients") to this group without invoking PowerShell.
Questions:
Note that: The Microsoft Graph API does not directly expose methods for assigning specific Exchange roles like "Mailbox Import Export" or "Mail Recipients" to security groups.
One workaround is to invoke PowerShell commands programmatically from C# using System.Management.Automation
and creating a Runspace
to run the Exchange cmdlets, such as New-RoleGroup
like below:
using System.Management.Automation;
using System.Management.Automation.Runspaces;
var runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
var cmd = new PSCommand();
cmd.AddCommand("New-RoleGroup");
cmd.AddArgument("mailbox-import-export");
cmd.AddArgument("Mailbox Import Export");
cmd.AddArgument("Mail Recipients");
cmd.AddArgument("admin@mail.com"); // Managed by
cmd.AddArgument("admin@mail.com"); // Members
var pipeline = runspace.CreatePipeline();
pipeline.Commands.Add(cmd);
var results = pipeline.Invoke();
runspace.Close();
Otherwise, use the Exchange Online PowerShell module from within C# code like below:
using System.Management.Automation;
using Microsoft.Exchange.WebServices.Data;
var ps = PowerShell.Create();
ps.AddScript("Connect-ExchangeOnline -UserPrincipalName admin@example.com -ShowProgress $true");
ps.Invoke();
// Now, you can add role assignments like in PowerShell:
ps.AddScript("New-RoleGroup -Name 'mailbox-import-export' -Roles 'Mailbox Import Export','Mail Recipients' -ManagedBy 'admin@mail.com' -Members 'admin@mail.com'");
ps.Invoke();