Enable-Mailbox against Exchange 2010 from a web application


A question that seems to keep popping up is how to run the Enable-Mailbox cmdlet from a web-application.  I have had a couple of cases on this recently, so here are the details on how to achieve this for Exchange 2010.  I do also have an example web application that works against Exchange 2007, which I may blog about at some point in the future (the technique is different and slightly more involved).

Exchange 2010 supports remote Powershell.  In fact, even when running PowerShell on the Exchange server, it is creating a remote runspace.  This actually makes programming against it a lot easier – at least, so long as you do not need to use pass-through authentication (this example application doesn’t – it requires you to provide your Exchange credentials).  NOTE: currently pass-through authentication does not work with WinRM – so it is impossible to implement this with Exchange 2010.  This should be addressed in a future update.

The web application consists of just one page.  The code reads the necessary configuration from textboxes on the HTML part of the page, so you’ll need to create a page with these textboxes:

TextBoxPowerShellUri: the URL for the remote Powershell (e.g. http://exchange.ex2k10.local/Powershell?serializationLevel=Full)
TextBoxExchangeUser: the user account with permissions to run the Enable-Mailbox cmdlet
TextBoxExchangePassword: the password for the Exchange account
TextBoxUser: the account to be mail-enabled
TextBoxExchangeDB: the database to be used for the mailbox

Other than the textboxes, you’ll need a button to submit the information.

The code is:

 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Text;
using System.Security;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{

    private WSManConnectionInfo ConnectionInfo()
    {
        string ConnectionUri = TextBoxPowerShellUri.Text;
        string sPassword = TextBoxExchangePassword.Text;
        SecureString sSPassword = new SecureString();

        foreach (char X in sPassword)
            sSPassword.AppendChar(X);

        PSCredential Credential = new PSCredential(TextBoxExchangeUser.Text, sSPassword);

        // Set the connection info
        WSManConnectionInfo ConInfo = new WSManConnectionInfo((new Uri(ConnectionUri)), "http://schemas.microsoft.com/powershell/Microsoft.Exchange", Credential);
        ConInfo.AuthenticationMechanism = AuthenticationMechanism.Default;
        return ConInfo;
    }

    private void EnableMailbox(string mailbox, string mailboxDatabase)
    {
        // Check that user is not already enabled
        if (MailboxEnabled(mailbox)) return;

        // Create a remote runspace
        using (Runspace EnableMailboxRunspace = RunspaceFactory.CreateRunspace(ConnectionInfo()))
        {
            EnableMailboxRunspace.Open();

            // Create a pipeline to process the commands
            using (Pipeline EnableMailboxPipeline=EnableMailboxRunspace.CreatePipeline())
            {
                Command cmdEnableMailbox=new Command("Enable-Mailbox");
                cmdEnableMailbox.Parameters.Add("Identity", @mailbox);
                cmdEnableMailbox.Parameters.Add("Database", @mailboxDatabase);
                EnableMailboxPipeline.Commands.Add(cmdEnableMailbox);
                EnableMailboxPipeline.Invoke();

                // Check for errors and report them
                PipelineReader<object> Errors=EnableMailboxPipeline.Error;
                if (Errors.Count>0)
                {
                    string sError="Error(s) occurred
"; foreach (object Error in (IEnumerable)Errors.Read()) { sError+=Error.ToString() + "
"; } Response.Write(sError); } } } } private bool MailboxEnabled(string mailbox) { // Check if the user is mail-enabled already // Create a remote runspace using (Runspace MailboxEnabledRunspace = RunspaceFactory.CreateRunspace(ConnectionInfo())) { MailboxEnabledRunspace.Open(); // Create a pipeline to process the commands using (Pipeline MailboxEnabledPipeline = MailboxEnabledRunspace.CreatePipeline()) { Command cmdEnableMailbox = new Command("Get-User"); cmdEnableMailbox.Parameters.Add("Identity", @mailbox); MailboxEnabledPipeline.Commands.Add(cmdEnableMailbox); Collection<PSObject> user = null; user=MailboxEnabledPipeline.Invoke(); // Check for errors and report them PipelineReader<object> Errors = MailboxEnabledPipeline.Error; if (Errors.Count > 0) { string sError = "Error(s) occurred
"; foreach (object Error in (IEnumerable)Errors.Read()) { sError += Error.ToString() + "
"; } Response.Write(sError); } foreach (PSMemberInfo info in user[0].Properties) { if (info.Name == "RecipientType") { if (string.Equals(info.Value.ToString(), "UserMailbox", StringComparison.OrdinalIgnoreCase)) { Response.Write("User is already mail-enabled
"); return true; } } } } } Response.Write("User is not mail-enabled
"); return false; } protected void Button1_Click1(object sender, EventArgs e) { try { EnableMailbox(TextBoxUser.Text, TextBoxExchangeDB.Text); } catch (Exception ex) { Response.Write(ex.ToString()); } finally { Response.Write("Finished."); } } }
Comments (0)

Skip to main content