PoshCode Logo PowerShell Code Repository

ASPX Mailbox (6 of 6) (modification of post by view diff)
embed code: <script type="text/javascript" src="http://PoshCode.org/embed/510"></script>download | new post

This is part 6 of a 6 part mailbox creation web site.
This site allows local administrators to create and delete mailboxes, and change email addresses. Save this as MailboxTaskResults.aspx.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Management.Automation;
  5. using System.Management.Automation.Runspaces;
  6. using System.Net.Mail;
  7.  
  8. public partial class MailboxTaskResults : System.Web.UI.Page
  9. {
  10.     protected void Page_Load(object sender, EventArgs e)
  11.     {
  12.         Response.Write("Here are the results of the  Domain mailbox task request...<br /><br />");
  13.         runposh("Add-PSSnapin Microsoft.Exchange.Management.PowerShell.Admin");
  14.  
  15. // Variable Definition
  16.         string strAdminID = Session["AdminID"].ToString();
  17.         string strUserDN = Session["DirPath"].ToString();
  18.         string strOldAddress = Session["OldAddress"].ToString();
  19.         string strNewAddress = Session["NewAddress"].ToString();
  20.         string strAction = Session["Action"].ToString();
  21.         string strAdminName = Session["AdminUser"].ToString();
  22.         string strLastName = Session["LastName"].ToString();
  23.         string strCompany = Session["Agency"].ToString();
  24.         string strDivisionOU = Session["DivisionOU"].ToString();
  25.         bool blKeepAddress = (bool)Session["blKeepAddress"];
  26.  
  27. // remove leading and trailing spaces from input strings
  28.         strAdminID = strAdminID.Trim();
  29.         strUserDN = strUserDN.Trim();
  30.         strLastName = strLastName.Trim();
  31.         strCompany = strCompany.Trim();
  32.         strOldAddress = strOldAddress.Trim();
  33.         strAction = strAction.Trim();
  34.         strAdminName = strAdminName.Trim();
  35.         strDivisionOU = strDivisionOU.Trim();
  36.  
  37. //Find out what we are doing
  38.         switch (strAction.ToLower())
  39.         {
  40.             case "create mailbox":
  41.                 fnCreateMailbox(strUserDN, strLastName, strCompany, strAdminName, strDivisionOU);
  42.                 break;
  43.             case "delete mailbox":
  44.                 fnDeleteMailbox(strAdminID, strUserDN, strAdminName);
  45.                 break;
  46.             case "change address":
  47.                 fnChangeAddress(strAdminID, strUserDN, strOldAddress, strNewAddress, strAdminName, strCompany, blKeepAddress);
  48.                 break;
  49.         }
  50.     }
  51.     protected void fnCreateMailbox(string strUserDN, string strLastName, string strCompany, string strAdminName, string strDivisionOU)
  52.     {
  53. /*
  54. * Function to create the mailbox
  55. * Requires the user's ADsPath, Last Name, and Company (Agency)
  56. */
  57.         string strAgency = "";
  58.         string strKey = "";
  59.         string strExchangeParam = "";
  60.  
  61.         int iLastNameNum = 0;
  62.  
  63.         Array arrExchParam;
  64.  
  65.         string strSubject = "";
  66.         string strBody = "";
  67.         string strAction = "";
  68.    
  69.         Collection<PSObject> colCreateResults;
  70.         #region Scripting Dictionary
  71. //Build the scripting dictionary for determining the server/storage group/database
  72.         Dictionary<string, string> objDict = new Dictionary<string, string>();
  73.         objDict.Add("ABC", "Server1:SG7:MBX7");
  74.         objDict.Add("DEF", "Server2:SG7:MBX7");
  75.         objDict.Add("AAS", "Server1:SG1:MBX1");
  76.         objDict.Add("AAD", "Server1:SG2:MBX2");
  77.         objDict.Add("DEP", "Server2:SG7:MBX7");
  78.         objDict.Add("DSS", "Server3:SG5:MBX5");
  79.         objDict.Add("DAD", "Server2:SG1:MBX1");
  80.         objDict.Add("DSQ", "Server2:SG2:MBX2");
  81.         objDict.Add("LOL", "Server3:SG4:MBX4");
  82.         objDict.Add("BRB", "Server2:SG5:MBX5");
  83.         objDict.Add("DNA", "Server2:SG6:MBX6");
  84.         objDict.Add("MOD", "Server3:SG3:MBX3");
  85.         objDict.Add("SOM", "Server3:SG4:MBX4");
  86.         objDict.Add("MOM", "Server2:SG1:MBX1");
  87.         objDict.Add("PAL", "Server3:SG6:MBX6");
  88.         objDict.Add("HIT", "Server3:SG1:MBX1");
  89.         objDict.Add("DOG", "Server3:SG2:MBX2");
  90.         objDict.Add("CAE", "Server1:SG3:MBX3");
  91.         objDict.Add("CAT", "Server1:SG4:MBX4");
  92.         objDict.Add("ENA", "Server3:SG4:MBX4");
  93.         objDict.Add("KAM", "Server2:SG3:MBX3");
  94.         objDict.Add("MAK", "Server2:SG4:MBX4");
  95.         objDict.Add("SJM", "Server2:SG7:MBX7");
  96.         objDict.Add("TIK", "Server4:SG1:MBX1");
  97.         objDict.Add("ILI", "Server4:SG2:MBX2");
  98.         objDict.Add("OOP", "Server4:SG3:MBX3");
  99.         objDict.Add("POW", "Server4:SG4:MBX4");
  100.         objDict.Add("WQA", "Server4:SG5:MBX5");
  101.         #endregion
  102.         #region Agency Selector
  103.         strAgency = strCompany.Trim().ToUpper();
  104.         strKey = strAgency;
  105.         #region HHS
  106.         if (strAgency == "HHS")
  107.         {
  108.             iLastNameNum = Convert.ToInt16(Convert.ToChar(strLastName.Substring(0, 1).ToUpper()));
  109.             if (iLastNameNum < 69)
  110.             {
  111.                 strKey = strAgency + "1"; //Put A through D in 1st Storage Group
  112.             }
  113.             else if (iLastNameNum < 73)
  114.             {
  115.                 strKey = strAgency + "2"; //Put E through H in 2nd Storage Group
  116.             }
  117.             else if (iLastNameNum < 77)
  118.             {
  119.                 strKey = strAgency + "3"; //Put I through L in 3rd Storage Group
  120.             }
  121.             else if (iLastNameNum < 81)
  122.             {
  123.                 strKey = strAgency + "4"; //Put M through P in 4th Storage Group
  124.             }
  125.             else if (iLastNameNum < 85)
  126.             {
  127.                 strKey = strAgency + "5"; //Put Q through T in 5th Storage Group
  128.             }
  129.             else
  130.             {
  131.                 strKey = strAgency + "6"; //Put U through Z in 6th Storage Group
  132.             }
  133.         }
  134.         #endregion
  135.         #region MDT
  136.         if (strAgency == "MDT")
  137.         {
  138.             iLastNameNum = Convert.ToInt16(Convert.ToChar(strLastName.Substring(0, 1).ToUpper()));
  139.             if (iLastNameNum < 70)
  140.             {
  141.                 strKey = strAgency + "1"; //Put A through E in 1st Storage Group
  142.             }
  143.             else if (iLastNameNum < 75)
  144.             {
  145.                 strKey = strAgency + "2"; //Put F through J in 2nd Storage Group
  146.             }
  147.             else if (iLastNameNum < 79)
  148.             {
  149.                 strKey = strAgency + "3"; //Put K through N in 3rd Storage Group
  150.             }
  151.             else if (iLastNameNum < 84)
  152.             {
  153.                 strKey = strAgency + "4"; //Put O through S in 4th Storage Group
  154.             }
  155.             else
  156.             {
  157.                 strKey = strAgency + "5"; //Put T through Z in 5th Storage Group
  158.             }
  159.         }
  160.         #endregion
  161.         #region DLI
  162.         if (strAgency == "DLI")
  163.         {
  164.             if (strDivisionOU == "BSD")
  165.             {
  166.                 strKey = strAgency + "2"; //Put BSD in the 2nd Storage Group
  167.             }
  168.             else if (strDivisionOU == "CSD")
  169.             {
  170.                 strKey = strAgency + "1"; //Put CSD in the 1st Storage Group
  171.             }
  172.             else if (strDivisionOU == "ERD")
  173.             {
  174.                 strKey = strAgency + "2"; //Put ERD in 2nd Storage Group
  175.             }
  176.             else if (strDivisionOU == "JSD")
  177.             {
  178.                 strKey = strAgency + "1"; //Put JSD in 1st Storage Group
  179.             }
  180.             else if (strDivisionOU == "RAD")
  181.             {
  182.                 strKey = strAgency + "2"; //Put RAD in 2nd Storage Group
  183.             }
  184.             else if (strDivisionOU == "UID")
  185.             {
  186.                 strKey = strAgency + "2"; //Put UID in 2nd Storage Group
  187.             }
  188.             else if (strDivisionOU == "WCC")
  189.             {
  190.                 strKey = strAgency + "1"; //Put RAD in 1st Storage Group
  191.             }
  192.         }
  193.         #endregion
  194.         #region DOA
  195.         if (strAgency == "DOA")
  196.         {
  197.             if (strDivisionOU == "ADM")
  198.             {
  199.                 strKey = strAgency + "1"; //Put ADM in the 1st Storage Group
  200.             }
  201.             else if (strDivisionOU == "ITSD")
  202.             {
  203.                 strKey = strAgency + "2"; //Put ITSD in 2nd Storage Group
  204.             }
  205.             else if (strDivisionOU == "MLOT")
  206.             {
  207.                 strKey = strAgency + "1"; //Put MLOT in the 1st Storage Group
  208.             }
  209.             else if (strDivisionOU == "MPERA")
  210.             {
  211.                 strKey = strAgency + "1"; //Put MPERA in 1st Storage Group
  212.             }
  213.             else if (strDivisionOU == "OPD")
  214.             {
  215.                 strKey = strAgency + "2"; //Put OPD in 2nd Storage Group
  216.             }
  217.             else if (strDivisionOU == "TRS")
  218.             {
  219.                 strKey = strAgency + "1"; //Put TRS in 1st Storage Group
  220.             }
  221.             else
  222.             {
  223.                 strKey = strAgency + "4"; //Put others in 4th Storage Group
  224.             }
  225.         }
  226.         #endregion
  227.         #region COR DNR DOJ DOR FWP
  228.         if ((strAgency == "COR") || (strAgency == "DNR") || (strAgency == "DOJ") || (strAgency == "DOR") || (strAgency == "FWP"))
  229.         {
  230.             iLastNameNum = Convert.ToInt16(Convert.ToChar(strLastName.Substring(0, 1).ToUpper()));
  231.             if (iLastNameNum < 78)
  232.             {
  233.                 strKey = strAgency + "1"; //Put A through M in 1st Storage Group
  234.             }
  235.             else
  236.             {
  237.                 strKey = strAgency + "2"; //Put N through Z in 2nd Storage Group
  238.             }
  239.         }
  240.         #endregion
  241.         #endregion
  242.         objDict.TryGetValue(strKey, out strExchangeParam);
  243.         arrExchParam = strExchangeParam.Split(':');
  244.  
  245.         Response.Write("Mailbox Creation attempt for " + strUserDN + " on Exchange server " + arrExchParam.GetValue(0));
  246.         {
  247. // Verify that exchange specific AD properties exist, and set them if they don't
  248.             strAction = "$user = [ADSI]^LDAP://" + strUserDN.Substring(1).Substring(0,strUserDN.Length -2) +"^";
  249.             strAction = strAction.Replace("^", "\"");
  250.             colCreateResults = runposh(strAction);
  251.             strAction = "$attribute = $user.msExchVersion; if (!$attribute){$user.put('msExchVersion', '4535486012416')};$user.setinfo()";
  252.             colCreateResults = runposh(strAction);
  253.             strAction = "$attribute  = $user.msExchRecipientDisplayType; if (!$attribute){$user.put('msExchRecipientDisplayType', '1073741824')};$user.setinfo()";
  254.             colCreateResults = runposh(strAction);
  255.             strAction = "$attribute  = $user.msExchRecipientTypeDetails; if (!$attribute){$user.put('msExchRecipientTypeDetails', '1')};$user.setinfo()";
  256.             colCreateResults = runposh(strAction);
  257. //Now, create the mailbox            
  258.             strAction = "Enable-Mailbox -identity " + strUserDN + " -Database " + arrExchParam.GetValue(0) + "\\" + arrExchParam.GetValue(1) + "\\" + arrExchParam.GetValue(2);
  259.             colCreateResults = runposh(strAction);
  260.             if (colCreateResults.Count > 0)
  261.             {
  262. //Disable Active Sync
  263.                 strAction = "Set-CASMailbox -identity " + strUserDN + " –ActiveSyncEnabled $false";
  264.                 colCreateResults = runposh(strAction);
  265.                 Response.Write("Mailbox creation was successful.<br /><br />");
  266.                 Response.Write("You will need to wait approximately 10 minutes for the mailbox to be available, due to Exchange and Active Directory replication latencies.<br /><br />");
  267.                 strSubject = strAdminName + " Created a mailbox";
  268.                 strBody = strAdminName + " created a mailbox associated with " + strUserDN + "\r\n\r\n";
  269.                 strBody = strBody + "This mailbox was created on " + arrExchParam.GetValue(0) + "\r\n\r\n";
  270.                 fnSendMail(strSubject, strBody);
  271.             }
  272.             else if (colCreateResults.Count == 0)
  273.             {
  274.                 Response.Write("<br /><br />There was an error creating the mailbox. Please contact the Service Desk at x2000 to report this error. Include the logon ID of the user you were attempting to create the mailbox for, and any error shown below.<br /><br />");
  275.                 strAction = "$error[0]";
  276.                 colCreateResults = runposh(strAction);
  277.                 if (colCreateResults.Count > 0)
  278.                 {
  279.                     string strErrorText = colCreateResults[0].ToString();
  280.                     Response.Write("The error is: <b><span style='color:Red'>" + strErrorText + "</b></span><br />");
  281.                 }
  282.                 else if (colCreateResults.Count == 0)
  283.                 {
  284.                     Response.Write("An unknown error occured.");
  285.                 }
  286.  
  287.             }
  288.         }
  289.     }
  290.     protected void fnDeleteMailbox(string strAdminID, string strUserDN, string strAdminName)
  291.     {
  292. /*
  293. * Function to Delete user's mailbox
  294. * Requires the Admin ID and user's ADsPath
  295. */
  296. // remove leading and trailing spaces from input strings
  297.         strAdminID = strAdminID.Trim();
  298.         strUserDN = strUserDN.Trim();
  299.         strAdminName = strAdminName.Trim();
  300.  
  301.         Collection<PSObject> colDeleteResults;
  302.         string strDeleteAction;
  303.         Response.Write("Mailbox Deletion attempt for " + strUserDN);
  304.         strDeleteAction = "$ConfirmPreference = 'none';set-Mailbox -Identity " + strUserDN + " -EmailAddresses $null -EmailAddressPolicyEnabled $false";
  305.         colDeleteResults = runposh(strDeleteAction);
  306.         strDeleteAction = "Disable-Mailbox -identity " + strUserDN + ";$ConfirmPreference = 'high'";
  307.         colDeleteResults = runposh(strDeleteAction);
  308.         if (colDeleteResults.Count == 0)
  309.         {
  310.             Response.Write("Mailbox deletion was successful.<br /><br /> You will need to wait approximately 10 minutes for the mailbox to disappear, due to Exchange and Active Directory replication latencies.");
  311.             string strSubject = strAdminName + " Deleted a mailbox";
  312.             string strBody = strAdminName + " deleted the mailbox associated with " + strUserDN;
  313.             fnSendMail(strSubject, strBody);
  314.         }
  315.         else if (colDeleteResults.Count != 0)
  316.         {
  317.             Response.Write("There was an error disabling the mailbox. Please contact the ITSD Customer Support Center at x2000 to report this error. Include the logon ID of the user whose mailbox you were attemting to disable");
  318.         }
  319.     }
  320.     protected void fnChangeAddress(string strAdminID, string strUserDN, string strOldAddress, string strNewAddress, string strAdminName, string strCompany, bool blKeepAddress)
  321.     {
  322. /*
  323. * Function to change User's Primary SMTP Address
  324. * Requires the user's ADsPath and desired address
  325. */
  326.  
  327. // remove leading and trailing spaces from input strings
  328.         strAdminID = strAdminID.Trim();
  329.         strUserDN = strUserDN.Trim();
  330.         strOldAddress = strOldAddress.Trim();
  331.         strNewAddress = strNewAddress.Trim();
  332.         strAdminName = strAdminName.Trim();
  333.  
  334.         Collection<PSObject> colChangeResults;
  335.  
  336.         string strChangeAction = "";
  337.         string strBody = "";
  338.         string strSubject = "";
  339.  
  340. // First, findout if requested address is already in use
  341.         strChangeAction = "Get-Recipient -Filter{EmailAddresses -eq '" + strNewAddress + "@domain.com'} |select Name";
  342.         colChangeResults = runposh(strChangeAction);
  343.         if (colChangeResults.Count == 0)
  344.         {
  345. // Requested address is available
  346.             Response.Write("Your requested address, " + strNewAddress + "@domain.com, is available<br />");
  347. // if blKeepAddress = false, delete old addresses in SMTP only
  348.             if (blKeepAddress == false)
  349.             {
  350.                 strChangeAction = "set-mailbox -identity " + strUserDN + " -PrimarySmtpAddress " + strNewAddress + "@domain.com -EmailAddressPolicyEnabled $false";
  351.                 colChangeResults = runposh(strChangeAction);
  352.                 do
  353.                 {
  354.                     strChangeAction = "get-mailbox -identity " + strUserDN + " |select PrimarySmtpAddress";
  355.                     colChangeResults = runposh(strChangeAction);
  356.                 } while (colChangeResults[0].ToString().Split('=')[1].Remove(colChangeResults[0].ToString().Split('=')[1].Length - 1).ToLower() != strNewAddress.ToLower() + "@domain.com");
  357.                 strChangeAction = "$mailbox = Get-Mailbox -identity " + strUserDN;
  358.                 colChangeResults = runposh(strChangeAction);
  359.                 strChangeAction = "$mailbox.EmailAddresses | foreach { if (!$_.IsPrimaryAddress -and ($_.PrefixString -eq 'SMTP')) {$mailbox.EmailAddresses -= $_}}";
  360.                 colChangeResults = runposh(strChangeAction);
  361.                 strChangeAction = "start-sleep 5";
  362.                 colChangeResults = runposh(strChangeAction);
  363.                 strChangeAction = "set-mailbox -identity " + strUserDN + " -EmailAddresses $mailbox.EmailAddresses";
  364.                 colChangeResults = runposh(strChangeAction);    
  365.             }
  366.             else
  367.             {
  368.                 strChangeAction = "set-mailbox -identity " + strUserDN + " -PrimarySmtpAddress " + strNewAddress + "@domain.com -EmailAddressPolicyEnabled $false";
  369.                 colChangeResults = runposh(strChangeAction);
  370.             }
  371.  
  372.             Response.Write("We have changed the primary SMTP address on " + strUserDN + "<br />");
  373.             Response.Write("From: " + strOldAddress + "<br />To: " + strNewAddress + "@domain.com<br />");
  374.             Response.Write("Please allow approximately 10 minutes for this change to replicate.");
  375.             strSubject = strOldAddress + " Address Change";
  376.             strBody = "SMTP Address change from " + strOldAddress + " to " + strNewAddress + "@domain.com on " + strUserDN + " by " + strAdminName + "\r\n\r\n";
  377.             fnSendMail(strSubject, strBody);
  378.         }
  379.         else if (colChangeResults.Count != 0)
  380.         {
  381. // Requested address is NOT available
  382.             Response.Write("A duplicate address exists");
  383.             Response.Write("Your requested address is: " + strNewAddress + "@domain.com<br />");
  384.             string strFoundName = colChangeResults[0].ToString().Substring(7).Substring(0, colChangeResults[0].ToString().Length - 8);
  385.             Response.Write("Duplicate address found at: " + strFoundName + "<br />");
  386.         }
  387.     }
  388.     protected void fnSendMail(string strSubject, string strBody)
  389.     {
  390. // Send mail to postmaster
  391.         MailMessage mail = new MailMessage();
  392.         mail.From = new MailAddress("postmaster@domain.com");
  393.         mail.To.Add(new MailAddress("postmaster@domain.com"));
  394.         mail.Subject = strSubject;
  395.         mail.Body = strBody;
  396.         SmtpClient client = new SmtpClient();
  397.         client.Host = "mail.domain.com";
  398.         client.Send(mail);
  399.     }
  400.     protected Collection<PSObject> runposh(string strCommand)
  401.     {
  402.         Runspace rs = GetRunspace();
  403.         Pipeline currentPipeline = GetPipeline(rs, strCommand);
  404.         if (currentPipeline.PipelineStateInfo.State == PipelineState.NotStarted)
  405.         {
  406.             Collection<PSObject> results = currentPipeline.Invoke();
  407.             currentPipeline.Dispose();
  408.             Cache.Remove("currentPipe");
  409.             return (results);
  410.         }
  411.         else
  412.         {
  413.             return null;
  414.         }
  415.     }
  416.     protected Runspace GetRunspace()
  417.     {
  418.         if (Cache["rs"] == null)
  419.         {
  420.             Runspace rs = RunspaceFactory.CreateRunspace();
  421.             rs.Open();
  422.             Cache["rs"] = rs;
  423.         }
  424.         return (Runspace)Cache["rs"];
  425.     }
  426.     protected Pipeline GetPipeline(Runspace rs, string strCommand)
  427.     {
  428.         if (Cache["currentPipe"] == null)
  429.         {
  430.             Pipeline currentPipeline = rs.CreatePipeline(strCommand);
  431.             Cache["currentPipe"] = currentPipeline;
  432.         }
  433.         return (Pipeline)Cache["currentPipe"];
  434.     }
  435. }

Submit a correction or amendment below (
click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.

Syntax highlighting:


Remember me