/CommandLine/ADModifyMain.cs
C# | 3072 lines | 2468 code | 316 blank | 288 comment | 181 complexity | 2118bbae88426453d678a4c781974638 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- using System;
- using System.DirectoryServices;
- using ADModify.Library;
- using System.Xml;
- using System.IO;
- using Microsoft.Win32;
-
-
- namespace ADModify
- {
-
- /// <summary>
- /// Main is the program entry point. In main we check for arguments and change global variables depending on what
- /// was entered. If we have in fact found valid attribute switches, then the GetDN method is called. This Method
- /// does the initial LDAP query to find the DN for all users matching the LDAP filter specified.
- ///
- /// Once the have the users we test all globals for a non null value for string and a true value for boolean. If
- /// these test true, then we call the specified method from the ModifyAttributes class and pass all necesarry parameters.
- /// Modification and reporting is done within the methods of the ModifyAttributes and LogFile classes.
- /// </summary>
-
-
-
- class ADModifyMain
- {
-
- //public variables
- //set all string values to null and all bool values to false
- //later on we test these conditions and execute the modify only if string values
- //are !null and bool values are true
-
- public static int usercount = 0;
- public static int querycount = 0;
-
- //ldap settings
- public static string servername = null;
- public static int pageSize = 1000;
-
- //Terminal Server Attributes
- public static string TSProfilePath = null;
- public static string TSFolderPath = null;
- public static string TSHomeDrive = null;
- public static bool TSEnable = false;
- public static bool TSDisable = false;
- public static bool RemoteEnable = false;
- public static bool RemoteDisable = false;
- public static bool RequirePermission = false;
- public static string program = null;
- public static string startIn = null;
- public static bool InteractWithSession = false;
- public static bool SetDisconnectTime = false;
- public static int DisconnectTime;
- public static bool SetMaxConnectionTime = false;
- public static int MaxConnectionTime;
- public static bool SetMaxIdleTime = false;
- public static int MaxIdleTime;
- public static bool SetEndSession = false;
- public static bool EndSession = false;
- public static bool SetOriginatingOnly = false;
- public static bool OriginatingOnly = false;
- public static bool SetConnectClientDrives = false;
- public static bool ConnectClientDrives = false;
- public static bool SetConnectClientPrinters = false;
- public static bool ConnectClientPrinters = false;
- public static bool SetDefaultToMainPrinter = false;
- public static bool DefaultToMainPrinter = false;
-
- //Exchange related attributes
- public static bool killmail = false;
- public static bool includeinrecipientpolicy = false;
- public static bool excludefromrecipientpolicy = false;
- public static bool includeinmailboxmanager = false;
- public static bool excludefrommailboxmanager = false;
- public static bool enablehttp = false;
- public static bool disablehttp = false;
- public static bool enablepop3 = false;
- public static bool disablepop3 = false;
- public static bool enableimap4 = false;
- public static bool disableimap4 = false;
- public static bool enablemapi = false;
- public static bool disablemapi = false;
- public static bool enablecachedmapi = false;
- public static bool EnableOMA = false;
- public static bool EnableUIS = false;
- public static bool EnableUTD = false;
- public static string smtpaddress = null;
- public static bool setasprimary = false;
- public static bool updatemail = false;
- public static bool removeaddress = false;
- public static bool keepprimary = false;
- public static string addresstoremove = null;
- public static bool showinaddresslists = false;
- public static bool hidefromaddresslists = false;
- public static bool SetMailboxRights = false;
- public static bool ClearMailboxRights = false;
- public static bool FixSendAs = false;
- public static bool GrantSelfAEA = false;
- public static bool RemoveAEAFromSelf = false;
- public static bool RemoveSendAs = false;
- public static bool GrantSelfFullAndRead = false;
- public static bool RemoveSelfFullAndRead = false;
- public static bool DumpMailboxRights = false;
-
- //User Account Settings
- public static bool disableaccount = false;
- public static bool enableaccount = false;
- public static bool PasswordNotRequired = false;
- public static bool SetPasswordNotRequired = false;
- public static bool SetPasswordNeverExpires = false;
- public static bool PasswordNeverExpires = false;
- public static bool MustChangePasswd = false;
- public static bool SetMustChangePassword = false;
- public static bool CannotChangePasswd = false;
- public static bool SetCannotChangePassword = false;
- public static bool UseReversibleEncryption = false;
- public static bool SetUseReversibleEncryption = false;
- public static bool SetRequireSmartCard = false;
- public static bool RequireSmartCard = false;
- public static bool SetCannotBeDelegated = false;
- public static bool CannotBeDelegated = false;
- public static bool SetUseDESEncryption = false;
- public static bool UseDESEncryption = false;
- public static bool SetDoNotRequireKerberosPreAuth = false;
- public static bool DoNotRequireKerberosPreAuth = false;
- public static bool AddMembersToGroup = false;
- public static bool SetAccountExpires = false;
- public static string ExpireTime = null;
- public static bool RemoveMembersFromGroup = false;
- public static string DNOfGroup = null;
- public static bool ModifyRDN = false;
- public static string NewRDN = null;
-
- //Permissions Settings
- public static bool Setallowinheritable = false;
- public static bool AllowInheritable = false;
- public static bool DumpDacl = false;
- public static bool DumpDaclInheritance = false;
-
- //custom attribute set
- public static string customAttributeName = null;
- public static string customAttributeValue = null;
- public static bool multi = false;
- public static bool remove = false;
-
-
- //undo mode
- public static bool UndoMode = false;
- public static string logFileName = null;
-
- //mailbox rights
- public static bool GrantSendAsRights = false;
- public static bool ImportMailboxRights = false;
- public static bool ModifyMailboxRights = false;
- public static bool RemoveMailboxRights = false;
- public static string Trustee = null;
- public static string Permission = null;
- public static bool Deny = false;
- public static bool MailboxRightsOverwrite = false;
-
- //timer
- public static float timeElapsed = 0;
-
- //progress bar
- public static int UserCountDividedWhole;
- public static float UserCountDividedDecimalCount;
- public static float UserCountDividedDecimalCountConst;
- public static int dots;
-
-
-
- /// <summary>
- ///
- /// ADModifyMain::GetDN
- ///
- /// Accepts:
- /// logWriter - Handle to Writer object for logging
- /// LDAPFilter - the LDAP filter used for object search
- /// SearchBase - the DN to begin the query
- /// subtree - boolean specifies either onelevel or subtree
- ///
- /// Returns:
- /// none
- ///
- /// GetDN accepts the Search Base, Scope, and LDAP Filter from args.
- /// GetDN runs the query and returns the list of users that match.
- /// At that point we test all public variables. If a value other than the default
- /// is set, we call ADModify!ModifyAttributes::* to modify the object and pass all
- /// appropriate arguments.
- /// </summary>
-
- static void GetDN(XmlWriter logWriter, string LDAPFilter, bool subtree, string SearchBase)
- {
-
- //Before doing anything, verify the server and base DN entered are valid
- if(servername!=null)
- {
- try
- {
- //do this to test if we can even connect to the server
- DirectoryEntry ent = new DirectoryEntry("LDAP://" + servername + "/" + SearchBase);
- string myTempVar = ent.Parent.ToString(); //if the servername is invalid, this line will raise an exception
- ent.Dispose();
- }
- catch(System.Exception caught)
- {
- if(caught.Message=="The server is not operational")
- {
-
- Console.WriteLine("\nAn error has occurred connecting to server " + servername + ".");
- Console.WriteLine("The error was: " + caught.Message + "\n");
-
- }
- else if(caught.Message=="A referral was returned from the server" || caught.Message=="There is no such object on the server")
- {
-
- Console.WriteLine("\nAn error has occured binding to Base DN " + SearchBase + ".");
- Console.WriteLine("The error was: " + caught.Message + ".");
- Console.WriteLine("Please enter a valid Base DN.\n");
-
- }
- else
- {
-
- Console.WriteLine("\nAn error has occurred binding to Active Directory.");
- Console.WriteLine("The error was: " + caught.Message + "\n");
-
- }
- return;
- }
- }
-
- //Initialize the log file
- LogFile log = new LogFile();
-
- //Check for mailbox rights dump mode and create logfile if necesarry
- XmlTextWriter DumpWriter = null;
- if(DumpMailboxRights)
- {
- if(File.Exists("mbxrights.xml"))
- {
-
- Console.WriteLine("\nThe file mbxrights.xml already exists. You must remove or rename this file before you can proceed.\n");
- return;
- }
- DumpWriter = new XmlTextWriter("mbxrights.xml", null);
- DumpWriter.WriteStartElement("MailboxRights");
- }
-
-
- //get OS version to determine supportability of TS modifications
- //string OSVersionFull = System.Environment.OSVersion.ToString();
- //string OSVersion = OSVersionFull.Substring(OSVersionFull.Length - 10, 10);
- //int OSVersionNoDots = Convert.ToInt32(OSVersion.Replace(".",""),10);
-
- //Check for Win2k3 so we know whether to enable terminal services options
- //get OS build to determine supportability of TS modifications
- //TODO: When longhorn releases we need to add their build number to this check
-
- System.OperatingSystem osInfo = System.Environment.OSVersion;
-
- //First things first... check for TS attributes. If there are any, check OS version before proceeding.
- if(TSProfilePath!=null | program!=null | startIn!=null | TSFolderPath!=null | TSHomeDrive!=null | TSEnable | TSDisable | RemoteEnable | RemoteDisable | SetDisconnectTime | SetMaxConnectionTime | SetMaxIdleTime | SetEndSession | SetOriginatingOnly | SetConnectClientDrives | SetConnectClientPrinters | SetDefaultToMainPrinter)
- {
- if (osInfo.Version.Build != 3790)
- {
- Console.WriteLine("Operating System must be at build 5.2.3790.0 or later to support this operation.\nCurrent OS build: " + osInfo.VersionString + "\n");
- return;
- }
- }
-
- //Also check for CDOEXM attributes. If there are any, make sure Exchange is installed.
- if(FixSendAs || GrantSelfAEA || RemoveAEAFromSelf || GrantSelfFullAndRead || RemoveSelfFullAndRead || DumpMailboxRights || ImportMailboxRights || ModifyMailboxRights || RemoveMailboxRights)
- {
- RegistryKey myRegKey = Registry.LocalMachine;
- RegistryKey mySubKey = myRegKey.OpenSubKey("Software\\Microsoft\\Exchange\\Setup");
- string ExchangeVersion = mySubKey.GetValue("NewestBuild").ToString();
- int ExchangeVersionInt = Convert.ToInt32(ExchangeVersion,10);
- if(ExchangeVersionInt<4417)
- {
- Console.WriteLine("Exchange Server must be installed and must be at build 4417 or later to support this modification.\nCurrent Exchange Build: " + ExchangeVersion + "\n");
- return;
- }
-
- }
-
- //bind to AD using the SearchBase specified by the user
- DirectoryEntry de = new DirectoryEntry("LDAP://" + SearchBase);
-
- //set searcher object with our LDAP filter
- DirectorySearcher src = new DirectorySearcher(LDAPFilter);
- src.SearchRoot = de;
-
- //set our search scope
- if(subtree)
- src.SearchScope = SearchScope.Subtree;
- else
- src.SearchScope = SearchScope.OneLevel;
-
- //Other settings for search
- src.PageSize = pageSize;
- src.PropertiesToLoad.Add("distinguishedName");
-
- SearchResultCollection results = null;
-
- //execute the query
- try
- {
- results = src.FindAll();
- }
- catch(System.Exception caught)
- {
- Console.WriteLine("An error occured while executing the query. The error was: {0}", caught.Message + "\n");
- return;
- }
-
-
-
- Console.WriteLine("\nIssuing Query....\n");
- if(results.Count == 1)
- {
- Console.WriteLine("1 item found matching the specified filter.");
- }
- if(results.Count >= 2)
- {
- Console.WriteLine(results.Count + " items found matching the specified filter.");
- }
- if(results.Count == 0)
- {
- Console.WriteLine("No items found matching the specified filter.\n");
- return;
- }
- Console.WriteLine("");
-
- //for progress bar
- float UserCountDivided = 50/(float)results.Count; //this number remains constant
- float UserCountDividedTemp = UserCountDivided; //this number we increment
- dots = 0; //number of dots shown so far on progress bar
- UserCountDividedWhole = 0; //number on left side of decimal to increment
- UserCountDividedDecimalCount = 0; //number on right side of decimal to increment
- UserCountDividedDecimalCountConst = 0; //number on right side of decimal, stays contstant
- string UserCountDividedDecimalCountString = null;
- string[] UserCountDividedString = UserCountDivided.ToString().Split('.'); //split at the decimal
-
- //calculate the whole and decimal increment counters
- UserCountDividedWhole = Convert.ToInt16(UserCountDividedString[0],10); //grab the whole number on the left
- if(UserCountDividedString.GetUpperBound(0) == 1)
- {
- UserCountDividedDecimalCountString = UserCountDividedString[1].Replace(".", "");
- UserCountDividedDecimalCountString = "." + UserCountDividedDecimalCountString;
- UserCountDividedDecimalCount = float.Parse(UserCountDividedDecimalCountString);
- }
- else
- {
- UserCountDividedDecimalCount = 0;
- }
-
- UserCountDividedDecimalCountConst = UserCountDividedDecimalCount;
-
- Console.WriteLine("");
- Console.WriteLine("0% 50% 100%");
- Console.WriteLine("|----|----|----|----|----|----|----|----|----|----|");
- Console.Write(".");
- dots++;
-
-
- //increment the user count
- usercount++;
-
- ModifyAttributes admod = new ModifyAttributes(); //from ADModify.Library.dll
- string UserDN;
-
- //iterate the query results
- for(int modusers=0; modusers<=results.Count-1; modusers++)
- {
-
- if(dots<=50) //just to be safe, make sure we're under out dots quota so we don't
- { //exceed the 100% mark
- for(int b=0; b<= UserCountDividedWhole-1; b++)
- {
- if(dots<=50)
- {
- Console.Write(".");
- dots++;
- }
- }
- if(UserCountDividedDecimalCount>=1)
- {
- if(dots<=50)
- {
- UserCountDividedDecimalCount--;
- Console.Write(".");
- dots++;
- }
- }
- UserCountDividedDecimalCount = UserCountDividedDecimalCount + UserCountDividedDecimalCountConst;
- }
-
- if(modusers==results.Count-1 & dots < 51) //sometimes the decimal math doesn't leave us with a
- { //51st dot so we have to add it ourselves.
- Console.Write(".");
- }
- if(modusers==results.Count-1) //finish off the progress bar
- {
- Console.WriteLine("");
- Console.WriteLine("");
- }
-
- UserDN = results[modusers].Path;
- string UserDNWithLDAP = UserDN;
- string UserDNWithoutLDAP = UserDNWithLDAP.Remove(0, 7); //trim the LDAP:// off the name in case we need to append servername
-
- //check for servername. If its null we just pass UserDN as UserDNWithLDAP.
- //If it has a value we append it and add the LDAP:// back
- if(servername==null)
- {
- UserDN = UserDNWithLDAP;
- }
- else
- {
- UserDN = "LDAP://" + servername + "/" + UserDNWithoutLDAP;
- }
-
- //test each public variable for a value, if a value other than null exists for string values or
- //a true value exists for boolean values then we loop the users through the applicable methods
-
-
- //Terminal Server Attributes
- if(TSProfilePath!=null)
- {
- admod.TSChangeTermServProfile(logWriter, UserDN, TSProfilePath);
- }
- if(TSFolderPath!=null & TSHomeDrive==null)
- {
- admod.TSChangeTermServFolder(logWriter, UserDN, TSFolderPath);
- }
- if(TSHomeDrive!=null)
- {
- admod.TSChangeTermServDrive(logWriter, UserDN, TSHomeDrive, TSFolderPath);
- }
- if(TSEnable)
- {
- admod.TSEnableLogon(logWriter, UserDN);
- }
- if(TSDisable)
- {
- admod.TSDisableLogon(logWriter, UserDN);
- }
- if(RemoteEnable)
- {
- admod.TSAllowRemoteControl(logWriter, UserDN, RequirePermission, InteractWithSession);
- }
- if(RemoteDisable)
- {
- admod.TSDisableRemoteControl(logWriter, UserDN);
- }
- if(SetDisconnectTime)
- {
- admod.TSMaxDisconnectedSessionTime(logWriter, UserDN, DisconnectTime);
- }
- if(program!=null)
- {
- admod.TSRunProgramAtStartup(logWriter, UserDN, program);
- }
- if(startIn!=null)
- {
- admod.TSRunProgramAtStartupStartIn(logWriter, UserDN, startIn);
- }
- if(SetMaxConnectionTime)
- {
- admod.TSMaxConnectionTime(logWriter, UserDN, MaxConnectionTime);
- }
- if(SetMaxIdleTime)
- {
- admod.TSMaxIdleTime(logWriter, UserDN, MaxIdleTime);
- }
- if(SetEndSession)
- {
- admod.TSEndSessionAction(logWriter, UserDN, EndSession);
- }
- if(SetOriginatingOnly)
- {
- admod.TSAllowReconnectAction(logWriter, UserDN, OriginatingOnly);
- }
- if(SetConnectClientDrives)
- {
- admod.TSConnectClientDrivesAtLogon(logWriter, UserDN, ConnectClientDrives);
- }
- if(SetConnectClientPrinters)
- {
- admod.TSConnectClientPrintersAtLogon(logWriter, UserDN, ConnectClientPrinters);
- }
- if(SetDefaultToMainPrinter)
- {
- admod.TSDefaultToMainPrinter(logWriter, UserDN, DefaultToMainPrinter);
- }
- //Exchange Related Attributes
- if(showinaddresslists)
- {
- admod.ShowInAddressLists(logWriter, UserDN);
- }
- if(hidefromaddresslists)
- {
- admod.HideFromAddressLists(logWriter, UserDN);
- }
- if(killmail)
- {
- admod.KillMail(logWriter, UserDN);
- }
- if(includeinrecipientpolicy)
- {
- admod.IncludeInRecipientPolicy(logWriter, UserDN);
- }
- if(excludefromrecipientpolicy)
- {
- admod.ExcludeFromRecipientPolicy(logWriter, UserDN);
- }
- if(includeinmailboxmanager)
- {
- admod.IncludeInMailboxManager(logWriter, UserDN);
- }
- if(excludefrommailboxmanager)
- {
- admod.ExcludeFromMailboxManager(logWriter, UserDN);
- }
- if(enablehttp)
- {
- admod.EnableHTTP(logWriter, UserDN);
- }
- if(disablehttp)
- {
- admod.DisableHTTP(logWriter, UserDN);
- }
- if(enablepop3)
- {
- admod.EnablePOP3(logWriter, UserDN);
- }
- if(disablepop3)
- {
- admod.DisablePOP3(logWriter, UserDN);
- }
- if(enableimap4)
- {
- admod.EnableIMAP4(logWriter, UserDN);
- }
- if(disableimap4)
- {
- admod.DisableIMAP4(logWriter, UserDN);
- }
- if(enablemapi)
- {
- admod.ChangeMAPISettings(logWriter, UserDN, "MAPI§1§0§§§§§§");
- }
- if(disablemapi)
- {
- admod.ChangeMAPISettings(logWriter, UserDN, "MAPI§0§0§§§§§§");
- }
- if(enablecachedmapi)
- {
- admod.ChangeMAPISettings(logWriter, UserDN, "MAPI§1§1§§§§§§");
- }
- if(smtpaddress!=null)
- {
- admod.SetSMTPAddress(logWriter, UserDN, smtpaddress, setasprimary);
- }
- if(updatemail==true)
- {
- admod.SetCustomAttribute(logWriter, UserDN, "mail", smtpaddress, false, false);
- }
- if(removeaddress)
- {
- if(keepprimary)
- {
- admod.RemoveEmailAddress(logWriter, UserDN, addresstoremove, true);
- }
- else
- {
- admod.RemoveEmailAddress(logWriter, UserDN, addresstoremove, false);
- }
- }
- if(SetMailboxRights)
- {
- admod.SetmsExchMailboxSecurityDescriptor(logWriter, UserDN);
- }
- if(GrantSendAsRights)
- {
- admod.AddSendAs(logWriter, UserDN, Trustee, Deny);
- }
- if(FixSendAs)
- {
- admod.GiveSendAsToUsersWithFullMBXAccess(logWriter, UserDN);
- }
- if(RemoveSendAs)
- {
- admod.RemoveSendAsFromUsersWithFullMBXAccess(logWriter, UserDN);
- }
- if(GrantSelfAEA)
- {
- admod.SetSelfAsAssociatedExternalAccount(logWriter, UserDN);
- }
- if(RemoveAEAFromSelf)
- {
- admod.RemoveAssociatedExternalAccountFromSelf(logWriter, UserDN);
- }
- if(GrantSelfFullAndRead)
- {
- admod.GrantSelfFullMailboxAccessAndRead(logWriter, UserDN);
- }
- if(RemoveSelfFullAndRead)
- {
- admod.RemoveFullMailboxAccessAndReadFromSelf(logWriter, UserDN);
- }
- if(DumpMailboxRights)
- {
- admod.DumpMailboxRights(logWriter, DumpWriter, UserDN);
- }
- if(ModifyMailboxRights)
- {
- admod.AddACEToMailboxRights(logWriter, UserDN, Trustee, Permission, Deny);
- }
- if(RemoveMailboxRights)
- {
- admod.RemoveACEFromMailboxRights(logWriter, UserDN, Trustee, Permission, Deny);
- }
-
-
- //User Account Settings
- if(disableaccount)
- {
- admod.DisableAccount(logWriter, UserDN);
- }
- if(enableaccount)
- {
- admod.EnableAccount(logWriter, UserDN);
- }
- if (SetPasswordNotRequired & PasswordNotRequired)
- {
- admod.SetPasswordNotRequired(logWriter, UserDN);
- }
- if (SetPasswordNotRequired & !PasswordNotRequired)
- {
- admod.DisablePasswordNotRequired(logWriter, UserDN);
- }
- if(SetPasswordNeverExpires)
- {
- admod.SetPasswordNeverExpires(logWriter, UserDN, PasswordNeverExpires);
- }
- if(SetMustChangePassword)
- {
- admod.MustChangePassword(logWriter, UserDN, MustChangePasswd);
- }
- if(SetCannotChangePassword)
- {
- admod.CannotChangePassword(logWriter, UserDN, CannotChangePasswd);
- }
- if(SetUseReversibleEncryption)
- {
- admod.StorePasswordWithReversibleEncryption(logWriter, UserDN, UseReversibleEncryption);
- }
- if(SetRequireSmartCard)
- {
- admod.SetRequireSmartCard(logWriter, UserDN, RequireSmartCard);
- }
- if(SetCannotBeDelegated)
- {
- admod.SetCannotBeDelegated(logWriter, UserDN, CannotBeDelegated);
- }
- if(SetUseDESEncryption)
- {
- admod.SetUseDESEncryption(logWriter, UserDN, UseDESEncryption);
- }
- if(SetDoNotRequireKerberosPreAuth)
- {
- admod.SetDoNotRequireKerberosPreAuth(logWriter, UserDN, DoNotRequireKerberosPreAuth);
- }
- if(AddMembersToGroup)
- {
- admod.AddToGroup(logWriter, UserDN, DNOfGroup);
- }
- if(RemoveMembersFromGroup)
- {
- admod.RemoveFromGroup(logWriter, UserDN, DNOfGroup);
- }
- if(ModifyRDN)
- {
- admod.SetRelativeDistinguishedName(logWriter, UserDN, NewRDN);
- }
-
-
- //Permissions Settings
- if(Setallowinheritable)
- {
- admod.AllowInheritablePermissions(logWriter, UserDN, AllowInheritable);
- }
-
-
- //custom attribute set
- if(customAttributeName!=null)
- {
- admod.SetCustomAttribute(logWriter, UserDN, customAttributeName, customAttributeValue, multi, remove);
- }
-
-
- }
-
- //finish up
- if(DumpMailboxRights)
- {
- DumpWriter.WriteEndElement();
- DumpWriter.Flush();
- DumpWriter.Close();
- }
- log.showResults();
- src.Dispose();
- return;
-
- }
-
-
-
-
-
-
-
-
- /// <summary>
- /// ADModifyMain::GiveCommandArgs
- ///
- /// Accepts:
- /// none
- /// Returns:
- /// none
- ///
- /// Displays command line usage back to the console.
- /// </summary>
- static void GiveCommandArgs()
- {
- Console.WriteLine("");
- Console.WriteLine("Active Directory Bulk Modify Tool Command Line Version 2.1");
- Console.WriteLine("");
- Console.WriteLine("Questions or Comments? ");
- Console.WriteLine("Email: admodify@microsoft.com");
- Console.WriteLine("");
- Console.WriteLine("ADModCmd runs an LDAP query against the specified AD container. The ");
- Console.WriteLine("modifications are then performed against the results of the query.");
- Console.WriteLine("");
- Console.WriteLine("Usage:");
- Console.WriteLine("");
- Console.WriteLine("admodcmd [-dn BaseDN] [-p pagesize] [-s] [-server servername]");
- Console.WriteLine(" [-f LDAPFilter] [modification]");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("Required:");
- Console.WriteLine("");
- Console.WriteLine("-dn BaseDN Base DN to begin the LDAP query.");
- Console.WriteLine("");
- Console.WriteLine("modification Modification to perform. ");
- Console.WriteLine(" See below for details.");
- Console.WriteLine("");
- Console.WriteLine("Optional:");
- Console.WriteLine("");
- Console.WriteLine("-p pagesize LDAP Page size to use for query.");
- Console.WriteLine("");
- Console.WriteLine("-s Denotes a subtree search ");
- Console.WriteLine(" (If -s is not specified, search ");
- Console.WriteLine(" defaults to onelevel).");
- Console.WriteLine("");
- Console.WriteLine("-server servername Denotes the server to make the changes ");
- Console.WriteLine(" to (If -server is not specified, ");
- Console.WriteLine(" changes are made locally if on a DC. ");
- Console.WriteLine(" If on a member, DNS is used to ");
- Console.WriteLine(" find a DC).");
- Console.WriteLine("");
- Console.WriteLine("-f LDAPFilter A Valid LDAP filter to use when ");
- Console.WriteLine(" enumerating objects (If -f is not ");
- Console.WriteLine(" specified, (objectClass=user) is");
- Console.WriteLine(" the default filter).");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("Modification Switches:");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("NOTE: Using the word \"null\" (without quotes) as an attribute value will ");
- Console.WriteLine(" clear the attribute.");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("============================");
- Console.WriteLine("|Terminal Server Attributes|");
- Console.WriteLine("============================");
- Console.WriteLine("");
- Console.WriteLine("Windows 2003 or later is required to modify Terminal Server attributes.");
- Console.WriteLine("");
- Console.WriteLine("-tsprofilepath ProfilePath Sets the users Terminal Server ");
- Console.WriteLine(" Profile path to the specified value.");
- Console.WriteLine("");
- Console.WriteLine("-tshomefolderpath FolderPath Sets the users Terminal Server home ");
- Console.WriteLine(" folder path to the specified value.");
- Console.WriteLine("");
- Console.WriteLine("-tsnetworkfolderpath driveLetter FolderPath ");
- Console.WriteLine(" Sets the users Terminal Server home");
- Console.WriteLine(" folder path to a network share.");
- Console.WriteLine(" driveLetter should be the drive that");
- Console.WriteLine(" FolderPath will be mapped to.");
- Console.WriteLine("");
- Console.WriteLine("-tsenable Enables the user for Terminal Server.");
- Console.WriteLine("");
- Console.WriteLine("-tsdisable Disables the user from using Terminal");
- Console.WriteLine(" Server.");
- Console.WriteLine("");
- Console.WriteLine("-enableremote -required -interact Enables Remote Control for the user.");
- Console.WriteLine(" The -required and -interact switches");
- Console.WriteLine(" are optional. If required is used,");
- Console.WriteLine(" \"Require Users Permission\" will be");
- Console.WriteLine(" checked. If -interact is specified, ");
- Console.WriteLine(" then \"Interact With The Session\" will");
- Console.WriteLine(" be checked.");
- Console.WriteLine("");
- Console.WriteLine("-disableremote Disables Remote Control for the user.");
- Console.WriteLine("");
- Console.WriteLine("-tsstartingprogram program Sets the program to start when the user");
- Console.WriteLine(" logs on to Terminal Server. ");
- Console.WriteLine("");
- Console.WriteLine("-tsstartin location Sets the location for the users startup");
- Console.WriteLine(" program to start in.");
- Console.WriteLine("");
- Console.WriteLine("-maxdisconnectedsession minutes");
- Console.WriteLine(" Sets the maximum disconnected session");
- Console.WriteLine(" time for the user in minutes. Setting");
- Console.WriteLine(" to 0 minutes indicates an unlimited");
- Console.WriteLine(" time.");
- Console.WriteLine("");
- Console.WriteLine("-maxconnectiontime minutes Sets the maximum connection time for ");
- Console.WriteLine(" the user in minutes. Setting to 0");
- Console.WriteLine(" indicates an unlimited time.");
- Console.WriteLine("");
- Console.WriteLine("-maxidletime minutes Sets the maximum idle time for the");
- Console.WriteLine(" user in minutes. Setting to 0 ");
- Console.WriteLine(" indicates an unlimited time. ");
- Console.WriteLine("");
- Console.WriteLine("-sessionlimitaction disconnect|end Specifies the action to take when ");
- Console.WriteLine(" a sessions limit has been reached.");
- Console.WriteLine(" Specify either disconnect (disconnect");
- Console.WriteLine(" the session) or end (end the session).");
- Console.WriteLine("");
- Console.WriteLine("-allowreconnect any|originating Specifies whether or not to allow a");
- Console.WriteLine(" reconnect from anywhere (any) or just");
- Console.WriteLine(" the originating client (originating).");
- Console.WriteLine("");
- Console.WriteLine("-tsconnectclientdrives yes|no Specifies whether or not to connect");
- Console.WriteLine(" client drives upon logon to a Terminal");
- Console.WriteLine(" Server session.");
- Console.WriteLine("");
- Console.WriteLine("-tsconnectclientprinters yes|no Specifies whether or not to connect");
- Console.WriteLine(" client printers upon logon to a ");
- Console.WriteLine(" Terminal Server session.");
- Console.WriteLine("");
- Console.WriteLine("-tsdefaulttomainprinter yes|no Specifies whether or not to default");
- Console.WriteLine(" to the main client printer.");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("=============================");
- Console.WriteLine("|Exchange Related Attributes|");
- Console.WriteLine("=============================");
- Console.WriteLine("");
- Console.WriteLine("-killmail Removes Exchange Attributes.");
- Console.WriteLine("");
- Console.WriteLine("-includeinrecipientpolicy Checks \"Automatically Update E-mail");
- Console.WriteLine(" Addresses Based on Recipient Policy\"");
- Console.WriteLine(" Check box.");
- Console.WriteLine("");
- Console.WriteLine("-excludefromrecipientpolicy Unchecks \"Automatically Update E-mail");
- Console.WriteLine(" Addresses Based on Recipient Policy\"");
- Console.WriteLine(" Check box.");
- Console.WriteLine("");
- Console.WriteLine("-hidefromaddresslists Hides the user from all Address Lists.");
- Console.WriteLine("");
- Console.WriteLine("-showinaddresslists Shows the user in address lists.");
- Console.WriteLine("");
- Console.WriteLine("-includeinmailboxmanager Includes the user in mailbox manager");
- Console.WriteLine(" policies.");
- Console.WriteLine("");
- Console.WriteLine("-excludefrommailboxmanager Excludes the user from mailbox manager");
- Console.WriteLine(" policies.");
- Console.WriteLine("");
- Console.WriteLine("-enablehttp Enables HTTP for the user.");
- Console.WriteLine("");
- Console.WriteLine("-disablehttp Disables HTTP for the user.");
- Console.WriteLine("");
- Console.WriteLine("-enablepop3 Enables POP3 for the user.");
- Console.WriteLine("");
- Console.WriteLine("-disablepop3 Disables POP3 for the user.");
- Console.WriteLine("");
- Console.WriteLine("-enableimap4 Enables IMAP4 for the user.");
- Console.WriteLine("");
- Console.WriteLine("-disableimap4 Disables IMAP4 for the user.");
- Console.WriteLine("");
- Console.WriteLine("The three MAPI settings below require that the users mailbox");
- Console.WriteLine("is homed on an Exchange 2003 SP2 or later server.");
- Console.WriteLine("");
- Console.WriteLine("-enablemapi Enables MAPI access for the user.");
- Console.WriteLine("");
- Console.WriteLine("-disablemapi Disables MAPI access for the user.");
- Console.WriteLine("");
- Console.WriteLine("-enablecachedmapi Enables MAPI access for users in");
- Console.WriteLine(" cached mode only.");
- Console.WriteLine("");
- Console.WriteLine("-addsmtp address -setasprimary -updatemail");
- Console.WriteLine(" Adds an SMTP address to the user.");
- Console.WriteLine(" Address will need to be in the form");
- Console.WriteLine(" of variable@domain.com (Information");
- Console.WriteLine(" on variable usage can be found below");
- Console.WriteLine(" under \"Variables\"). Specify the ");
- Console.WriteLine(" optional setasprimary switch to set ");
- Console.WriteLine(" the address as primary (default ");
- Console.WriteLine(" is secondary). Use the -updatemail");
- Console.WriteLine(" switch to also set the E-mail address");
- Console.WriteLine(" on the ADU&C General tab.");
- Console.WriteLine("");
- Console.WriteLine("-removeaddress address Removes any address that matches the");
- Console.WriteLine(" specified filter. Wild cards are");
- Console.WriteLine(" allowed. Examples would be:\n");
- Console.WriteLine(" smtp:*@domain.com");
- Console.WriteLine(" smtp:*@doma??.com\n");
- Console.WriteLine(" Normal * and ? wildcard matching");
- Console.WriteLine(" rules apply. Please note that this");
- Console.WriteLine(" can be used to remove any match found");
- Console.WriteLine(" in the users Proxy Addresses list,");
- Console.WriteLine(" not just SMTP addresses. Matches are");
- Console.WriteLine(" case-insensitive.");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("----Mailbox Rights----");
- Console.WriteLine("");
- Console.WriteLine("-setmailboxrights Sets msExchMailboxSecurityDescriptor.");
- Console.WriteLine(" KB 324353");
- Console.WriteLine("");
- Console.WriteLine("-fixsendas Grants Send-As rights to users with");
- Console.WriteLine(" Full Mailbox Access and Read.");
- Console.WriteLine(" KB 327274");
- Console.WriteLine("");
- Console.WriteLine("-removefixsendas Removes Send-As rights from users");
- Console.WriteLine(" with Full Mailbox Access and Read.");
- Console.WriteLine(" Undo for KB 327274");
- Console.WriteLine("");
- Console.WriteLine("-grantselfaea Grants Associated External Account");
- Console.WriteLine(" privileges to SELF. KB 278966");
- Console.WriteLine("");
- Console.WriteLine("-removeaeafromself Removes Associated External Account");
- Console.WriteLine(" from SELF. Undo for KB 278966");
- Console.WriteLine("");
- Console.WriteLine("-grantselffullandread Grants Full Mailbox Access and Read");
- Console.WriteLine(" to SELF. KB 304935");
- Console.WriteLine("");
- Console.WriteLine("-removefullandread Removes Full Mailbox Access and Read");
- Console.WriteLine(" from SELF. Undo for KB 304935");
- Console.WriteLine("");
- Console.WriteLine("-dumpmailboxrights Dumps all permissions in Mailbox Rights");
- Console.WriteLine(" to a file called mbxrights.xml.");
- Console.WriteLine("");
- Console.WriteLine("-importmailboxrights overwrite|append");
- Console.WriteLine(" Imports mailbox rights from the");
- Console.WriteLine(" mbxrights.xml created by the");
- Console.WriteLine(" -dumpmailboxrights switch. When using");
- Console.WriteLine(" this switch, the -dn switch is not");
- Console.WriteLine(" required. Overwrite will remove all");
- Console.WriteLine(" non-inherited ACE's before importing,");
- Console.WriteLine(" append will not. This switch only");
- Console.WriteLine(" imports non-inherited mailbox");
- Console.WriteLine(" rights.");
- Console.WriteLine("");
- Console.WriteLine("-addtomailboxrights DOMAIN\\USER ACCESS_MASK -deny (Optional)");
- Console.WriteLine(" Adds an account to mailbox rights with");
- Console.WriteLine(" the specified permissions masks. The ");
- Console.WriteLine(" optional -deny switch specfies a deny");
- Console.WriteLine(" entry, default is an allow entry.");
- Console.WriteLine(" Valid Access Masks:");
- Console.WriteLine("");
- Console.WriteLine(" ACE_MB_FULL_ACCESS");
- Console.WriteLine(" ACE_MB_DELETE_MB_STORAGE");
- Console.WriteLine(" ACE_MB_READ_PERMISSIONS");
- Console.WriteLine(" ACE_MB_CHANGE_PERMISSION");
- Console.WriteLine(" ACE_MB_TAKE_OWNERSHIP");
- Console.WriteLine("");
- Console.WriteLine("-removefrommailboxrights DOMAIN\\USER ACCESS_MASK -deny (optional)");
- Console.WriteLine(" Removes the specified mask from");
- Console.WriteLine(" DOMAIN\\USER in mailbox rights. The");
- Console.WriteLine(" -deny switch specifies a deny entry,");
- Console.WriteLine(" default is an allow entry.");
- Console.WriteLine(" Valid Access Masks:");
- Console.WriteLine("");
- Console.WriteLine(" ACE_MB_FULL_ACCESS");
- Console.WriteLine(" ACE_MB_DELETE_MB_STORAGE");
- Console.WriteLine(" ACE_MB_READ_PERMISSIONS");
- Console.WriteLine(" ACE_MB_CHANGE_PERMISSION");
- Console.WriteLine(" ACE_MB_TAKE_OWNERSHIP");
- Console.WriteLine(" ALL");
- Console.WriteLine("");
- Console.WriteLine(" The ALL Mask will remove all permissions");
- Console.WriteLine(" for the specified user.");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("=======================");
- Console.WriteLine("|User Account Settings|");
- Console.WriteLine("=======================");
- Console.WriteLine("");
- Console.WriteLine("-enableaccount Enables the user account.");
- Console.WriteLine("");
- Console.WriteLine("-disableaccount Disables the user account.");
- Console.WriteLine("");
- Console.WriteLine("-passwordnotrequired yes|no Specifies whether to set the password");
- Console.WriteLine(" not required option.");
- Console.WriteLine("");
- Console.WriteLine("-passwordneverexpires yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Password Never Expires\" box.");
- Console.WriteLine("");
- Console.WriteLine("-mustchangepassword yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"User Must Change Password at Next");
- Console.WriteLine(" Logon\" box.");
- Console.WriteLine("");
- Console.WriteLine("-cannotchangepassword yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"User Cannot Change Password\" box.");
- Console.WriteLine("");
- Console.WriteLine("-usereversibleencryption yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Store Password Using Reversible ");
- Console.WriteLine(" Encryption\" box.");
- Console.WriteLine("");
- Console.WriteLine("-smartcardrequired yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Smart Card is Required for ");
- Console.WriteLine(" Interactive Logon\" box.");
- Console.WriteLine("");
- Console.WriteLine("-cannotbedelegated yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Account is Sensitive and Cannot");
- Console.WriteLine(" be Delegated\" box.");
- Console.WriteLine("");
- Console.WriteLine("-usedesencryption yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Use DES Encryption Types for This");
- Console.WriteLine(" Account\" box.");
- Console.WriteLine("");
- Console.WriteLine("-donotrequirekerberospreauth yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Do Not Require Kerberos ");
- Console.WriteLine(" Preauthentication\" box.");
- Console.WriteLine("");
- Console.WriteLine("-addtogroup DNOfGroup Adds the user to the specified group.");
- Console.WriteLine("");
- Console.WriteLine("-removefromgroup DNOfGroup Removes the user from the specified");
- Console.WriteLine(" group.");
- Console.WriteLine("");
- Console.WriteLine("-allowinheritable yes|no Specifies whether to check or uncheck");
- Console.WriteLine(" the \"Allow inheritable permissions to");
- Console.WriteLine(" propagate to this object\" box.");
- Console.WriteLine("");
- Console.WriteLine("-modrdn NewRDN Changes the users Relative Distinguished");
- Console.WriteLine(" Name (CN). Variable usage is required.");
- Console.WriteLine(" To change an RDN to LastName, FirstName");
- Console.WriteLine(" use the following syntax:");
- Console.WriteLine(" -modrdn \"%'sn'%, %'givenName'%\"");
- Console.WriteLine("");
- Console.WriteLine("===================");
- Console.WriteLine("|Custom Attributes|");
- Console.WriteLine("===================");
- Console.WriteLine("");
- Console.WriteLine("The -custom switch allows you to name the attribute you wish to modify. This");
- Console.WriteLine("operation is only supported against attributes of the following type:");
- Console.WriteLine("");
- Console.WriteLine("Boolean");
- Console.WriteLine("Case Insensitive String");
- Console.WriteLine("Distinguished Name");
- Console.WriteLine("DN Binary");
- Console.WriteLine("IA5-String");
- Console.WriteLine("Integer");
- Console.WriteLine("Numerical String");
- Console.WriteLine("Unicode String");
- Console.WriteLine("");
- Console.WriteLine("Syntax: ");
- Console.WriteLine("[-custom attributeName attributeValue -multi|-remove]");
- Console.WriteLine("");
- Console.WriteLine("attributeName The name of the attribute you wish");
- Console.WriteLine(" to modify.");
- Console.WriteLine("");
- Console.WriteLine("attributeValue The value to give the attribute.");
- Console.WriteLine("");
- Console.WriteLine("-multi (optional) Specifies a multi-valued append. If");
- Console.WriteLine(" the attribute being modified is multi-");
- Console.WriteLine(" valued this switch needs to be used. ");
- Console.WriteLine(" Otherwise, the value will be ");
- Console.WriteLine(" overwritten, not appended.");
- Console.WriteLine("");
- Console.WriteLine("-remove (optional) Specifies a multi-valued remove. If");
- Console.WriteLine(" the attribute being modified is multi-");
- Console.WriteLine(" valued and -remove is used, then only");
- Console.WriteLine(" the specified value will get removed.");
- Console.WriteLine("");
- Console.WriteLine("Example for setting description attribute:");
- Console.WriteLine("");
- Console.WriteLine("-custom description \"IT Department\"");
- Console.WriteLine("");
- Console.WriteLine("");
- Console.WriteLine("==========");
- Console.WriteLine("|Variables|");
- Console.WriteLine("==========");
- Console.WriteLine("");
- Console.WriteLine("Variable usage is allowed when building attributes. Variables can be based ");
- Console.WriteLine("off of almost any current Active Directory attribute, as long as it has a ");
- Console.WriteLine("value. Variables are seperated from literal values using the % sign.");
- Console.WriteLine("Variables must also be enclosed in a single tick (').");
- Console.WriteLine("");
- Console.WriteLine("This example shows how to set homeDirectory to the path c:\\test\\username, ");
- Console.WriteLine("where username is the users sAMAccountName:");
- Console.WriteLine("");
- Console.WriteLine("-custom homeDirectory c:\\test\\%'sAMAccountName'%");
- Console.WriteLine("");
- Console.WriteLine("It is also possible to pull only a specified number of characters from the ");
- Console.WriteLine("attribute as well. Just specify the number of characters you want to use");
- Console.WriteLine("after the %, and before the \"'\". The following example shows how to add ");
- Console.WriteLine("an SMTP address of FirstInitial.LastName@domain.com:");
- Console.WriteLine("");
- Console.WriteLine("-addsmtp %1'givenName'%.%'sn'%@domain.com");
- Console.WriteLine("");
- Console.WriteLine("If a % or ' is needed as a literal value, simply use the forward slash (/)");
- Console.WriteLine("as an escape character:");
- Console.WriteLine("");
- Console.WriteLine("Example:");
- Console.WriteLine("This is a percent sign: /%");
- Console.WriteLine("");
- Console.WriteLine("The above line will end up being: This is a percent sign: %");
- Console.WriteLine("");
- Console.WriteLine("There may be times where you need a literal forward slash before the");
- Console.WriteLine("percentage or single tick characters, usually when the forward slash");
- Console.WriteLine("needs to be followed by a variable. The syntax for this is //% or //'");
- Console.WriteLine("An example would be adding an MS Mail address:");
- Console.WriteLine("");
- Console.WriteLine("ms:PO/SERVER//%'mailNickName'");
- Console.WriteLine("");
- Console.WriteLine("===========");
- Console.WriteLine("|Undo Mode|");
- Console.WriteLine("===========");
- Console.WriteLine("");
- Console.WriteLine("Changes made with ADModify can be undone, as long as the xml log file that");
- Console.WriteLine("logged the changes still exists. These log files are typically located in");
- Console.WriteLine("the same folder as the admodify executable.");
- Console.WriteLine("");
- Console.WriteLine("Syntax:");
- Console.WriteLine("[-undo logfilename -server servername]");
- Console.WriteLine("");
- Console.WriteLine("-undo logfilename Specifes the log file that contains the");
- Console.WriteLine(" changes to be undone.");
- Console.WriteLine("");
- Console.WriteLine("-server servername (optional) Specifies the DC to write the changes");
- Console.WriteLine(" to. If left blank changes are written");
- Console.WriteLine(" locally if the local machine is a DC.");
- Console.WriteLine(" If not, DNS is used to find one.");
- Console.WriteLine("");
- Console.WriteLine("For information on users that were skipped during an undo process, refer");
- Console.WriteLine("to the undo.log file.");
- Console.WriteLine("");
- Console.WriteLine("For more information on sample usage, please refer to the ADModify help.");
- Console.WriteLine("");
- Console.WriteLine("");
-
- }
-
-
-
-
-
-
-
-
-
-
- /// <summary>
- /// ADModifyMain::Main
- ///
- /// Accepts:
- /// args - command line arguments passed by the user
- /// Returns:
- /// nothing
- ///
- /// Here we accept all command line arguments and set the global variables for these
- /// arguments accordingly. Control is then given to the GetDN function.
- /// </summary>
- [STAThread]
- static void Main(string[] args)
- {
-
- LogFile log = new LogFile();
-
- DateTime endTime;
- TimeSpan finalCount;
-
- string RawDateTime = System.DateTime.Now.ToString();
- RawDateTime = RawDateTime.Replace(" ","").Replace("/","").Replace(":","");
- string logFileName = RawDateTime + ".xml";
- XmlTextWriter logWriter = new XmlTextWriter(logFileName, null);
-
-
- logWriter.WriteStartDocument(false);
- logWriter.WriteDocType("LogFile", null, null, null);
- logWriter.WriteStartElement("XmlRoot", logFileName);
-
- DateTime startTime = System.DateTime.Now;
-
- bool haveDN = false; //flip this bit when we have a base DN passed
- int numberargs = args.Length;
- string LDAPFilter = "(objectClass=user)"; //default to this in case a filter is not specified
- bool subtree = false; //default to a onelevel search
- bool bitflipped = false; //if any valid attribute switch is given we flip this bit
- string SearchBase = "blank";
-
-
-
- //loop through args and set the necesarry information
- for(int i=0; i < numberargs; i++)
- {
- switch(args[i].ToLower())
- {
- case "/?":
- case "-?":
- bitflipped = true;
- GiveCommandArgs();
- return;
- case "-server":
- try
- {
- servername = args[i+1];
- i++;
- }
- catch(System.IndexOutOfRangeException)
- {
- Console.WriteLine("Please enter a server name after the -servername switch.");
- return;
- }
- break;
- case "-f":
- try
- {
- LDAPFilter = args[i+1];
- i++;
- }
- catch(System.IndexOutOfRangeException)
- {
- Console.WriteLine("Please enter an LDAP filter after the -filter switch.");
- return;
- }
- break;
- case "-p":
- try
- {
- pageSize = Convert.ToInt32(args[i+1],10);
- if(pageSize>1000 || pageSize==0)
- {
- Console.WriteLine("Please enter …
Large files files are truncated, but you can click here to view the full file