This article will provide C# code that will allow you to leverage the Exchange Management Shell to add a Microsoft Exchange 2010/2013 User to a specified group. In order to use the code below, you must have the Exchange Management tools installed on the machine which will be running this code. Exchange Management Tools installation instructions can be found here. The code below can be used in creating either a console or windows forms application using SharpDevelop IDE. In creating your own application, you will want to ensure you have imported the required libraries using the code directly below.
/* * Created by SharpDevelop. * User: mmarable * Date: 2/25/2015 * Time: 10:35 AM */ using System; using System.Security; using System.Windows.Forms; using System.Management.Automation; using System.Management.Automation.Runspaces;
Once you have imported all the required libraries, simply paste the function below in your code and start using it as needed.
public Boolean AddUserToGroup(string Alias, string GroupName) { Boolean success = false; InitialSessionState rsConfig = InitialSessionState.CreateDefault(); rsConfig.ImportPSModule(new string[] { "ActiveDirectory" }); Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig); myRunSpace.Open(); Pipeline pipeLine = myRunSpace.CreatePipeline(); Command myCommand = new Command("Add-ADGroupMember"); myCommand.Parameters.Add("Identity", GroupName); myCommand.Parameters.Add("Member", Alias); pipeLine.Commands.Add(myCommand); try { pipeLine.Invoke(); } catch (Exception ex) { lblError.Text = ex.Message; } finally { myRunSpace.Dispose(); success = true; } return success; }