Showing posts with label DomainCommander. Show all posts
Showing posts with label DomainCommander. Show all posts

Friday, March 25, 2016

Way more fun AD C# functions...

This goes well with my last post!
     public void UnlockUser(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             else  
             {  
               MessageBox.Show(usr.DisplayName + "'s account not locked, " + "last logon at " + usr.LastLogon.ToString() + ", " + "user has " + usr.BadLogonCount.ToString() + " bad password attempts.");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void ResetUsersPassword(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string resetPasswordString = "Are you sure you want to reset " + usr.DisplayName + "'s password?";  
             yesNoDialog = MessageBox.Show(resetPasswordString, "Password Reset", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               usr.SetPassword("Password1");  
               usr.ExpirePasswordNow();  
               MessageBox.Show(usr.DisplayName + "'s password has been reset.");  
             }  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void PsLoggedOn(string psLoggedOnArgs, string pcname)  
     {  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         DialogResult yesNoDialog;  
         yesNoDialog = MessageBox.Show("Would you like to run psLoggedIn also?", "psLoggedOn?", MessageBoxButtons.YesNo);  
         if (yesNoDialog == DialogResult.Yes)  
         {  
           try  
           {  
             System.Diagnostics.Process proc = new System.Diagnostics.Process();  
             proc.EnableRaisingEvents = false;  
             proc.StartInfo.FileName = "psLoggedOn";  
             proc.StartInfo.UseShellExecute = false;  
             if (PcNameIsNotNullOrVoid(pcname))  
             {  
               proc.StartInfo.Arguments = " " + backslashes + pcname + " " + psLoggedOnArgs;  
             }  
             proc.StartInfo.RedirectStandardOutput = true;  
             proc.Start();  
             //string tasklist = proc.StandardOutput.ReadToEnd();  
             MessageBox.Show(proc.StandardOutput.ReadToEnd());  
             //proc.WaitForExit();  
           }  
           catch (Exception tasklistException)  
           {  
             MessageBox.Show(tasklistException.Message);  
           }  
         }  
       }  
     }  
     public List<string> GetGroups(string user, string fQDomainName, string ou)  
     {  
       List<string> groupList = new List<string>();  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             var groups = usr.GetGroups();  
             foreach (Object gr in groups)  
             {  
               groupList.Add(gr.ToString());  
               //MessageBox.Show(gr.ToString());  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
           return groupList;  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
           return groupList;  
         }  
       }  
       return groupList;  
     }  
     public void DisableAccount(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string disableAccountString = "Are you sure you want to disable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(disableAccountString + userInfoString, "Disable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == true)  
               {  
                 usr.Enabled = false;  
                 usr.SetPassword("sdP32*&^kna0^d$");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "disabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been disabled");  
                 string removeGroupsString = "Would you like to remove " + usr.DisplayName + " from all AD groups and move to Disabled Users OU?";  
                 yesNoDialog = MessageBox.Show(removeGroupsString, "Remove AD Groups?", MessageBoxButtons.YesNo);  
                 if (yesNoDialog == DialogResult.Yes)  
                 {  
                   RemoveUserFromAllGroups(user, fQDomainName, ou);  
                   MoveToDisabledUsersOU(usr.DistinguishedName, disabledUsersOU);  
                   MessageBox.Show(usr.DisplayName + " has been removed from all AD groups and moved to Disabled Users.");  
                 }  
                 string deleteTSProfilesString = "Would you like to delete " + usr.DisplayName + "'s profiles from all the Terminal Servers?";  
                 yesNoDialog = MessageBox.Show(deleteTSProfilesString, "Delete TS Profiles?", MessageBoxButtons.YesNo);  
                 if (yesNoDialog == DialogResult.Yes)  
                 {  
                   DiskTools dt = new DiskTools();  
                   dt.DeleteTSProfiles(usr.SamAccountName.ToLower());  
                   MessageBox.Show(usr.DisplayName + "'s profiles are being deleted from all terminal servers.");  
                 }  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already disabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
       else  
       {  
         MessageBox.Show("User not found");  
       }  
     }  
     public void DisableAccountTemp(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string disableAccountString = "Are you sure you want to temporarily disable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(disableAccountString + userInfoString, "Temporarily Disable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == true)  
               {  
                 usr.Enabled = false;  
                 usr.SetPassword("sdP32*&^kna0^d$");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "disabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been disabled");  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already disabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void EnableAccount(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string enableAccountString = "Are you sure you want to enable " + usr.DisplayName + "'s account?";  
             string userInfoString = "\n\nUSER INFO:\n" + "\nName:\t\t" + usr.DisplayName + "\nTitle:\t\t" + usr.title + "\nDepartment\t" + usr.department + "\nCompany:\t" + usr.company + "\nOffice:\t\t" + usr.office + "\nEmail:\t\t" + usr.EmailAddress + "\nLogin:\t\t" + usr.SamAccountName + "\nDescription:\t" + usr.Description;  
             yesNoDialog = MessageBox.Show(enableAccountString + userInfoString, "Enable Account?", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               if (usr.Enabled == false)  
               {  
                 usr.Enabled = true;  
                 //usr.SetPassword("Password1");  
                 string toDay = DateTime.Today.Date.ToString();  
                 usr.Description = "enabled " + toDay.Substring(0, toDay.IndexOf(" ")) + " " + Environment.UserName;  
                 usr.Save();  
                 MessageBox.Show(usr.DisplayName + "'s account has been enabled");  
               }  
               else  
               {  
                 MessageBox.Show(usr.DisplayName + "'s account is already enabled");  
               }  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  
     public void AddUserToGroup(string user, string fQDomainName, string ou, string groupName)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName))  
           {  
             UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
             GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);  
             group.Members.Add(usr);  
             group.Save();  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void RemoveUserFromGroup(string user, string fQDomainName, string ou, string groupName)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName))  
           {  
             UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
             GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, groupName);  
             group.Members.Remove(usr);  
             group.Save();  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void RemoveUserFromAllGroups(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           List<string> groupList = GetGroups(user, fQDomainName, ou);  
           foreach (object group in groupList)  
           {  
             if (!string.Equals(group.ToString(), "Domain Users"))  
             {  
               RemoveUserFromGroup(user, fQDomainName, ou, group.ToString());  
             }  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
     }  
     public void MoveToDisabledUsersOU(string userDN, string newOU)  
     {  
       //Move an object from one ou to another  
       DirectoryEntry eLocation = new DirectoryEntry("LDAP://" + userDN);  
       DirectoryEntry nLocation = new DirectoryEntry("LDAP://" + newOU);  
       string newName = eLocation.Name;  
       eLocation.MoveTo(nLocation, newName);  
       nLocation.Close();  
       eLocation.Close();  
     }  
     public string RandomPassword(int passwordLength)  
     {  
       string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";  
       char[] chars = new char[passwordLength];  
       Random rd = new Random();  
       for (int i = 0; i < passwordLength; i++)  
       {  
         chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];  
       }  
       return new string(chars);  
     }  
     public void PopulateADLocations(string fQDomainName, string ou)  
     {  
       foreach (string location in Properties.Settings.Default.ADLocations)  
       {  
         //populations AD PhysicalDeliveryOfficeName field based on group membership  
         RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
         myRunSpace.Open();  
         Pipeline ps = myRunSpace.CreatePipeline();  
         Command getADGroupMemberCommand = new Command("Get-ADGroupMember");  
         CommandParameter getADGroupMemberArgs = new CommandParameter("Identity", location);  
         getADGroupMemberCommand.Parameters.Add(getADGroupMemberArgs);  
         ps.Commands.Add(getADGroupMemberCommand);  
         Command setADUserCommand = new Command("Set-ADUser");  
         CommandParameter setADUserArgs = new CommandParameter("Office", location);  
         setADUserCommand.Parameters.Add(setADUserArgs);  
         ps.Commands.Add(setADUserCommand);  
         // Call the PowerShell.Invoke() method to run the   
         // commands of the pipeline.  
         StringBuilder output = new StringBuilder();  
         foreach (PSObject result in ps.Invoke())  
         {  
           output.AppendLine(result.ToString());  
         } // End foreach.  
         MessageBox.Show(output.ToString() + location + " complete.");  
         myRunSpace.Dispose();  
       }  
     }  
     public void PopulateADTitles(string fQDomainName, string ou)  
     {  
       foreach (string title in Properties.Settings.Default.ADTitles)  
       {  
         //populations AD Title field based on group membership  
         RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
         Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
         myRunSpace.Open();  
         Pipeline ps = myRunSpace.CreatePipeline();  
         Command getADGroupMemberCommand = new Command("Get-ADGroupMember");  
         CommandParameter getADGroupMemberArgs = new CommandParameter("Identity", title);  
         getADGroupMemberCommand.Parameters.Add(getADGroupMemberArgs);  
         ps.Commands.Add(getADGroupMemberCommand);  
         Command setADUserCommand = new Command("Set-ADUser");  
         CommandParameter setADUserArgs = new CommandParameter("Title", title.TrimEnd('s'));  
         setADUserCommand.Parameters.Add(setADUserArgs);  
         ps.Commands.Add(setADUserCommand);  
         // Call the PowerShell.Invoke() method to run the   
         // commands of the pipeline.  
         StringBuilder output = new StringBuilder();  
         foreach (PSObject result in ps.Invoke())  
         {  
           output.AppendLine(result.ToString());  
         } // End foreach.  
         MessageBox.Show(output.ToString() + title + " complete.");  
         myRunSpace.Dispose();  
       }  
    }  

Get Some AD info in C#

     private void getUsersADInfoToolStripMenuItem_Click(object sender, EventArgs e)  
     {  
       UserTools ut = new UserTools();  
       var combinedList = new List<string>();  
       combinedList.AddRange(ut.GetADUserInfo(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       combinedList.Add("");  
       combinedList.Add("GROUP MEMBERSHIPS: ");  
       combinedList.AddRange(ut.GetGroups(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       //ListBoxForm.ShowList(combinedList, "AD Info for " + ut.GetFullName(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
       TextBoxForm.ShowText(string.Join<string>(Environment.NewLine, combinedList), "AD Info for " + ut.GetFullName(profileNameBox.Text, fullyQualifiedDomainName, organizationalUnit));  
     }  
     public List<string> GetADUserInfo(string user, string fQDomainName, string ou)  
     {  
       List<string> resultList = new List<string>();  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             resultList.Add("NAME:\t\t" + usr.DisplayName);  
             resultList.Add("TITLE:\t\t" + usr.title);  
             resultList.Add("DEPARTMENT:\t" + usr.department);  
             resultList.Add("COMPANY:\t" + usr.company);  
             resultList.Add("OFFICE:\t\t" + usr.office);  
             resultList.Add("EMAIL:\t\t" + usr.EmailAddress);  
             resultList.Add("LOGIN:\t\t" + usr.SamAccountName);  
             resultList.Add("PROFILE:\t" + usr.HomeDirectory);  
             if(!string.IsNullOrEmpty(usr.Description))  
             {  
               resultList.Add("DESCRIPTION:\t" + usr.Description);  
             }  
             usr.Dispose();  
           }  
           else resultList.Add("");  
           ctx.Dispose();  
           return resultList;  
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
           resultList.Add("");  
           return resultList;  
         }  
       }  
       else resultList.Add("");  
       return resultList;  
     }  
     public string GetSamAccountName(string user, string fQDomainName, string ou)  
     {  
       string samAccountName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             samAccountName = usr.SamAccountName.ToString();  
             usr.Dispose();  
           }  
           else samAccountName = "";  
           ctx.Dispose();  
           return samAccountName;  
         }  
         catch (Exception getSamAccountNameException)  
         {  
           MessageBox.Show(getSamAccountNameException.Message);  
           samAccountName = "";  
           return samAccountName;  
         }  
       }  
       else samAccountName = "";  
       return samAccountName;  
     }  
     public string GetFullName(string user, string fQDomainName, string ou)  
     {  
       string fullName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             fullName = usr.Name.ToString();  
             usr.Dispose();  
           }  
           else fullName = "";  
           ctx.Dispose();  
           return fullName;  
         }  
         catch (Exception getFullNameException)  
         {  
           MessageBox.Show(getFullNameException.Message);  
           fullName = "";  
           return fullName;  
         }  
       }  
       else fullName = "";  
       return fullName;  
     }  
     public string GetEmailAddress(string user, string fQDomainName, string ou)  
     {  
       string emailAddress;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             emailAddress = usr.EmailAddress.ToString();  
             usr.Dispose();  
           }  
           else emailAddress = "";  
           ctx.Dispose();  
           return emailAddress;  
         }  
         catch (Exception getEmailException)  
         {  
           MessageBox.Show(getEmailException.Message);  
           emailAddress = "";  
           return emailAddress;  
         }  
       }  
       else emailAddress = "";  
       return emailAddress;  
     }  
     public string GetManager(string user, string fQDomainName, string ou)  
     {  
       string managerName;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             managerName = GetFullName(usr.manager, fullyQualifiedDomainName, organizationalUnit);  
             usr.Dispose();  
           }  
           else managerName = "";  
           ctx.Dispose();  
           return managerName;  
         }  
         catch (Exception getManager)  
         {  
           MessageBox.Show(getManager.Message);  
           managerName = "";  
           return managerName;  
         }  
       }  
       else managerName = "";  
       return managerName;  
     }  
     public string GetCompany(string user, string fQDomainName, string ou)  
     {  
       string company;  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
           if (usr != null)  
           {  
             company = usr.company.ToString();  
             usr.Dispose();  
           }  
           else company = "";  
           ctx.Dispose();  
           return company;  
         }  
         catch  
         {  
           MessageBox.Show("Warning: Company not set!");  
           company = "";  
           return company;  
         }  
       }  
       else company = "";  
       return company;  
     }  

Wednesday, March 23, 2016

Restart a remote computer's print spooler and delete it's print jobs via C#

Custom functions not included PcNameIsNotNullOrVoid(pcname), CleanPCName(pcname), variables such as cshare, etc. Utilizes windows built in psservice.exe.
     public void RestartTheSpooler(string pcname)  
     {  
       try  
       {  
         StopTheSpooler(pcname);  
         Thread.Sleep(1500);  
         //Thread stopSpoolThread = new Thread(new ThreadStart(stopTheSpooler));  
         //stopSpoolThread.Start();  
         DeletePrintJobs(pcname);  
         StartTheSpooler(pcname);  
       }  
       catch (Exception spoolerException)  
       {  
         MessageBox.Show(spoolerException.Message);  
       }  
     }  
     public void StopTheSpooler(string pcname)  
     {  
       pcname = CleanPCName(pcname);  
       //stop spooler  
       System.Diagnostics.Process stopspooler = new System.Diagnostics.Process();  
       stopspooler.EnableRaisingEvents = false;  
       stopspooler.StartInfo.FileName = "psservice";  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         stopspooler.StartInfo.Arguments = backslashes + pcname + " stop spooler";  
         stopspooler.Start();  
         stopspooler.WaitForExit();  
       }  
     }  
     public void DeletePrintJobs(string pcname)  
     {  
       //delete print jobs  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         if (Directory.Exists(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\printers\"))  
         {  
           Directory.Delete(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\printers", true);  
         }  
         Directory.CreateDirectory(backslashes + pcname + @"\" + cshare + @"\windows\system32\spool\PRINTERS");  
       }  
     }  
     public void StartTheSpooler(string pcname)  
     {  
       //start spooler  
       System.Diagnostics.Process startspooler = new System.Diagnostics.Process();  
       startspooler.EnableRaisingEvents = false;  
       startspooler.StartInfo.FileName = "psservice";  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         startspooler.StartInfo.Arguments = backslashes + pcname + " start spooler";  
         startspooler.Start();  
       }  
     }  

Thursday, October 15, 2015

List and Delete printers with WMI and .NET

Works, but looks like it was a work in progress I never completely finished.
     public List<string> WMIGetPrinterList(string pcname)  
     {  
       string query = "Select * from Win32_Printer";  
       pcname = CleanPCName(pcname);  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       if (PcNameIsNotNullOrVoid(pcname))  
       {  
         try  
         {  
           ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
           scope.Connect();  
           ObjectQuery obquery = new ObjectQuery(query);  
           ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
           foreach (ManagementObject obj in searcher.Get())  
           {  
             try  
             {  
               resultList.Add("Name: " + obj["Name"].ToString());  
               resultList.Add("Port: " + obj["PortName"].ToString());  
               resultList.Add("DeviceID: " + obj["DeviceID"].ToString());  
               resultList.Add("DriverName: " + obj["DriverName"].ToString());  
               if (obj["Shared"].ToString().Equals(true.ToString()))  
               {  
                 resultList.Add("Share Name: " + obj["ShareName"].ToString());  
               }  
               //resultList.Add("Status: " + obj["Status"].ToString());  
               //resultList.Add("Printer Status: " + obj["PrinterStatus"].ToString());  
               //resultList.Add("Printer State: " + obj["PrinterState"].ToString());  
               //int state = Int32.Parse(obj["ExtendedPrinterStatus"].ToString());  
               //switch (state)  
               //{  
               //  case 1: //Other  
               //    resultList.Add("Other");  
               //    break;  
               //  case 2: //Unknown  
               //    resultList.Add("Unknown 2");  
               //    break;  
               //  case 7: //Offline  
               //    resultList.Add("Offline");  
               //    break;  
               //  case 9: //error  
               //    resultList.Add("Error");  
               //    break;  
               //  case 11: //Not Available  
               //    break;  
               //  default:  
               //    resultList.Add("None of the above.");  
               //    break;  
               //}  
               resultList.Add("");  
             }  
             catch  
             {  
               resultList.Add("Unknown");  
             }  
           }  
         }  
         catch (Exception e)  
         {  
           MessageBox.Show(e.Message);  
         }  
       }  
       //resultList.Sort();  
       return resultList;  
     }  
     //Deletes the printer  
     public void WMIDeletePrinter(string pcname, string printerName)  
     {  
       try  
       {  
         if (PcNameIsNotNullOrVoid(pcname) && !string.IsNullOrEmpty(printerName))  
         {  
           string query = @"SELECT * FROM Win32_Printer WHERE Name = '" + printerName.Replace("\\", "\\\\") + "'";  
           pcname = CleanPCName(pcname);  
           ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
           scope.Connect();  
           SelectQuery obquery = new SelectQuery(query);  
           ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
           ManagementObjectCollection oObjectCollection = searcher.Get();  
           if (oObjectCollection.Count > 0)  
           {  
             foreach (ManagementObject oItem in oObjectCollection)  
             {  
               oItem.Delete();  
               MessageBox.Show(oItem["Name"].ToString() + " deleted.");  
             }  
           }  
           else  
           {  
             MessageBox.Show("Printer not Found");  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
       }  
     }    

Get currently logged in user with WMI and .NET

     public List<string> WMIGetLoggedOnUser(string pcname)  
     {  
       string query = "select UserName from Win32_ComputerSystem";  
       pcname = CleanPCName(pcname);  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       try  
       {  
         ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         foreach (ManagementObject obj in searcher.Get())  
         {  
           try  
           {  
             resultList.Add(obj["UserName"].ToString());  
           }  
           catch  
           {  
             resultList.Add("Unknown");  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
       }  
       resultList.Sort();  
       return resultList;  
     }  

Get service tag on a Dell machine in WMI and .NET

     public List<string> WMIGetServiceTag(string pcname)  
     {  
       string query = "Select * from Win32_SystemEnclosure";  
       pcname = CleanPCName(pcname);    
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       try  
       {  
         ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         foreach (ManagementObject obj in searcher.Get())  
         {  
           try  
           {  
             resultList.Add(obj["SerialNumber"].ToString());  
           }  
           catch  
           {  
             resultList.Add("Unknown");  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
       }  
       resultList.Sort();  
       return resultList;  
     }  

Getting Installed software and hotfixes remotely in .NET with WMI

     public List<string> WMIGetInstalledSoftware(string pcname)  
     {  
       string query = "select Name from win32_product";  
       pcname = CleanPCName(pcname);  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       try  
       {  
         ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         foreach (ManagementObject obj in searcher.Get())  
         {  
           try  
           {  
             resultList.Add(obj["Name"].ToString());  
           }  
           catch  
           {  
             resultList.Add("Unknown");  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
       }  
       resultList.Sort();  
       return resultList;  
     }  
     public List<string> WMIGetHotfixes(string pcname)  
     {  
       string query = "select HotFixID from Win32_QuickFixEngineering";  
       pcname = CleanPCName(pcname);  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       try  
       {  
         ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         foreach (ManagementObject obj in searcher.Get())  
         {  
           try  
           {  
             if (!obj["HotFixID"].Equals(null))  
             {  
               if (!obj["HotFixID"].ToString().Contains("File 1"))  
               {  
                 resultList.Add(obj["HotFixID"].ToString());  
               }  
             }  
           }  
           catch  
           {  
             resultList.Add("Unknown");  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
       }  
       resultList.Sort();  
       return resultList;  
     }  

Get Mapped drives remotely in .NET with WMI

     public List<string> GetMappedDrives(string pcname)  
     {  
       pcname = CleanPCName(pcname);  
       List<string> resultList = WMIGetMappedDrives(pcname);  
       List<string> resultList2 = RegGetMappedDrives(pcname);  
       resultList.Add("");  
       List<string> combinedList = new List<string>();  
       combinedList.AddRange(resultList);  
       combinedList.AddRange(resultList2);  
       return combinedList;  
     }  
     private List<string> WMIGetMappedDrives(string pcname)  
     {  
       List<string> resultList = new List<string>();  
       string query = "Select * from Win32_MappedLogicalDisk";  
       StringBuilder queryResult = new StringBuilder();  
       try  
       {  
         ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         foreach (ManagementObject obj in searcher.Get())  
         {  
           try  
           {  
             resultList.Add(obj["Name"].ToString() + " " + obj["ProviderName"]);  
           }  
           catch  
           {  
             resultList.Add("Unknown");  
           }  
         }  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
       }  
       //resultList.Sort();  
       return resultList;  
     }  
     private List<string> RegGetMappedDrives(string pcname)  
     {  
       string sid = WmiGetUserSID(pcname, WmiGetExplorerProcessOwner(pcname));  
       pcname = CleanPCName(pcname);  
       RegistryKey regKey;  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       try  
       {  
         regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, pcname).OpenSubKey(sid + @"\\Network");  
         //PrintKeys(rk);  
         foreach (string subKeyName in regKey.GetSubKeyNames())  
         {  
           try  
           {  
             string strPath = regKey.OpenSubKey(subKeyName).GetValue("RemotePath").ToString();  
             resultList.Add(subKeyName + ": " + strPath);  
           }  
           catch  
           {  
             resultList.Add("Unknown");  
           }  
         }  
         regKey.Close();  
         resultList.Sort();  
         regKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, pcname).OpenSubKey(sid + @"\\Volatile Environment");  
         resultList.Add(regKey.GetValue("HOMEDRIVE").ToString() + " " + regKey.GetValue("HOMESHARE").ToString() + " (HOMEDRIVE setting)");  
         regKey.Close();  
       }  
       catch //(Exception e)  
       {  
         //MessageBox.Show(e.GetType().Name + ": " + e.Message);  
         resultList.Add("");  
       }  
       return resultList;  
     }  
     private string WmiGetUserSID(string pcname, string domainBslashAccount)  
     {  
       string domain, user;  
       domain = domainBslashAccount.Substring(0, domainBslashAccount.IndexOf(@"\"));  
       user = domainBslashAccount.Substring(domainBslashAccount.IndexOf(@"\") + 1);  
       //string query = "Select * from Win32_UserAccount" + " Where Name='hadye' and Domain='domain'";  
       string query = "Select * from Win32_UserAccount" + " Where Name='" + user + "' and Domain='" + domain + "'";  
       ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
       string sid = "unknown";  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       pcname = CleanPCName(pcname);  
       try  
       {  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         foreach (ManagementObject obj in searcher.Get())  
         {  
           try  
           {  
             sid = obj["SID"].ToString();  
             return sid;  
           }  
           catch (Exception e)  
           {  
             MessageBox.Show(e.Message);  
             return sid;  
           }  
         }  
         return sid;  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
         return "SID unknown";  
       }  
     }  
     private string WmiGetExplorerProcessOwner(string pcname)  
     {  
       string query = "Select * from Win32_Process" + " Where Name='explorer.exe'"; // and SessionID=0"; sessionid=0 is not correct on widnows7  
       ManagementScope scope = new ManagementScope(backslashes + pcname + @"\root\cimv2");  
       StringBuilder queryResult = new StringBuilder();  
       List<string> resultList = new List<string>();  
       pcname = CleanPCName(pcname);  
       try  
       {  
         scope.Connect();  
         ObjectQuery obquery = new ObjectQuery(query);  
         ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, obquery);  
         //MessageBox.Show(searcher.Get().Count.ToString());  
         if (searcher.Get().Count >= 0)  
         {  
           ManagementObjectCollection processList = searcher.Get();  
           foreach (ManagementObject obj in processList)  
           {  
             string[] argList = new string[] { string.Empty, string.Empty };  
             int returnVal = Convert.ToInt32(obj.InvokeMethod("GetOwner", argList));  
             if (returnVal == 0)  
             {  
               // return DOMAIN\user  
               string owner = argList[1] + "\\" + argList[0];  
               return owner;  
             }  
           }  
         }  
         else  
         {  
           return @"localhost\administrator";  
         }  
         return @"localhost\administrator";  
       }  
       catch (Exception e)  
       {  
         MessageBox.Show(e.Message);  
         return @"localhost\administrator";  
       }  
     }  

Monday, April 20, 2015

Changelog

 ----------  
 2015.4.20  
 Added Tools -> System Tools -> Remote Command Line  
 (Brings up an interactive dos command line on remote pc)  

Thursday, April 9, 2015

Reset a user's password in AD with C#.NET

     public void ResetUsersPassword(string user, string fQDomainName, string ou)  
     {  
       if (!string.IsNullOrEmpty(user))  
       {  
         try  
         {  
           PrincipalContext ctx = new PrincipalContext(ContextType.Domain, fQDomainName, ou);  
           UserPrincipalsEx usr = UserPrincipalsEx.FindByIdentity(ctx, user);  
   
           if (usr != null)  
           {  
             DialogResult yesNoDialog;  
             string resetPasswordString = "Are you sure you want to reset " + usr.DisplayName + "'s password?";  
             yesNoDialog = MessageBox.Show(resetPasswordString, "Password Reset", MessageBoxButtons.YesNo);  
             if (yesNoDialog == DialogResult.Yes)  
             {  
               usr.SetPassword("Password1");  
               usr.ExpirePasswordNow();  
               MessageBox.Show(usr.DisplayName + "'s password has been reset.");  
             }  
             if (usr.IsAccountLockedOut())  
             {  
               usr.UnlockAccount();  
               MessageBox.Show(usr.DisplayName + "'s account unlocked");  
             }  
             usr.Dispose();  
           }  
           ctx.Dispose();  
   
         }  
         catch (Exception unlockException)  
         {  
           MessageBox.Show(unlockException.Message);  
         }  
       }  
     }  

My solution to disable popup blocker(or any registry setting in HKCU) on a remote machine on an IE zone, without GPO.

So basically, the C# writes a Batch file on the user's Desktop that the user must double click so it runs under their credentials, the Batch file then creates a .reg file on the desktop that it in turn runs to change the registry setting in HKCU, then it deletes the .reg and then itself. I was proud of this a few years ago when I wrote it with the 3 nested syntaxes and all. As you can see it relies on other custom methods I wrote, but what you need to do to replicate should be clear.

     public void DisablePopupBlocker(string pcname, string profile)  
     {  
       try  
       {  
         if (PcNameIsNotNullOrVoid(pcname) && !string.IsNullOrEmpty(profile))  
         {  
           pcname = CleanPCName(pcname);  
           profile = CheckForProfileDotDomain(pcname, profile);  
           //string filename = backslashes + pcname + @"\" + cshare + @"\Documents and Settings\" + profile + @"\Desktop\Disable PopUp Blocker.bat";  
           string filename = GetDesktopLocation(profile) +profile + @"\Desktop\Disable PopUp Blocker.bat";  
           if (File.Exists(filename))  
           {  
             File.Delete(filename);  
           }  
           try  
           {  
             using (StreamWriter writer = new StreamWriter(filename))  
             {  
               writer.WriteLine(@"@echo off");  
               writer.WriteLine(@"");  
               writer.WriteLine(@"echo Windows Registry Editor Version 5.00 >popup.reg");  
               writer.WriteLine(@"echo ;Pop up blocker disable >>popup.reg");  
               writer.WriteLine(@"echo [HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\2] >>popup.reg");  
               writer.WriteLine("echo \"1809\"=dword:00000003 >>popup.reg");  
               writer.WriteLine("echo \"2200\"=dword:00000000 >>popup.reg");  
               writer.WriteLine("echo \"1609\"=dword:00000000 >>popup.reg");  
               writer.WriteLine("echo \"2101\"=dword:00000000 >>popup.reg");  
               writer.WriteLine(@"");  
               writer.WriteLine(@"regedit.exe /s popup.reg");  
               writer.WriteLine(@"");  
               writer.WriteLine(@"del /q popup.reg");  
               writer.WriteLine(@"del %0");  
               writer.Flush();  
               writer.Close();  
               MessageBox.Show("Created Disable PopUp Blocker.bat on " + profile + "'s Desktop.");  
               writer.Dispose();  
             }  
           }  
           catch (IOException ioe)  
           {  
             MessageBox.Show(ioe.Message);  
           }  
   
         }  
       }  
       catch (Exception popupException)  
       {  
         MessageBox.Show(popupException.Message);  
       }  
     }  

Example of how to call Powershell Pipeline in C# and bring in Exchange SnapIn

     public List<string> getBlockedSenders()  
     {  
       RunspaceConfiguration rsConfig = RunspaceConfiguration.Create();  
       PSSnapInException snapInException = null;  
       PSSnapInInfo info = rsConfig.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", out snapInException);  
       Runspace myRunSpace = RunspaceFactory.CreateRunspace(rsConfig);  
       myRunSpace.Open();  
       Pipeline ps = myRunSpace.CreatePipeline();  
   
       Command getSenderFilterConfigCommand = new Command("Get-SenderFilterConfig");  
       ps.Commands.Add(getSenderFilterConfigCommand);  
   
       Command selectObjectCommand = new Command("Select-Object");  
       CommandParameter selectObjectArgs = new CommandParameter("ExpandProperty", "BlockedSenders");  
       selectObjectCommand.Parameters.Add(selectObjectArgs);  
       ps.Commands.Add(selectObjectCommand);  
   
       Command outStringCommand = new Command("Out-String");  
       CommandParameter outStringArgs = new CommandParameter("Stream");  
       outStringCommand.Parameters.Add(outStringArgs);  
       ps.Commands.Add(outStringCommand);  
   
       List<string> output = new List<string>();  
       foreach (PSObject result in ps.Invoke())  
       {  
         output.Add(result.ToString());  
       }  
   
       myRunSpace.Dispose();  
       return output;  
     }  

Thursday, October 23, 2014

New Exchange Features

First Exchange feature added using powershell in the background. Just a simple Get-Mailbox command on selected user for now to get my framework working. Most of the hard work is done, will be relatively simple to port existing scripts I've written to run as single click buttons against selected users.

The first features to be implemented will be:

Un/Blacklist Email Domain
Un/Blacklist Email Sender
Un/Whitelist Email Domain
Un/Whitelist Email Sender
Show current Outlook Spam Filter Settings
Enable or Disable Outlook Web Access for a selected user
Set user's Outlook/Lync photo
Setup Exchange Unified Messaging Voicemail for selected user


Release Changelog

----------
2014.10.23

Added Tools -> User Tools -> Populate AD Locations
//Populates PhysicalDeliveryOfficeName based on group memberships defined in application properties
Added Tools -> User Tools -> Populate AD Titles
//Populates Title based on group memberships defined in application properties
Added Tools -> Exchange Tools -> Get Mailbox

----------
2014.1.23

Update strings and OU's for AKA
Change MapRBJDrives to MapPY48forms
Fixed date in description when enabling/disabling users

----------
2013.7.21

Bugfix release

----------
2013.7.17

Updated Termination email templates BCC line to include ID Card Access Requests email

----------
2013.7.16

Added Tools -> User Tools -> Send Termination Email
Added Tools -> Network Tools -> DHCP Renew (ipconfig /renew)

----------
2013.6.21

Added Tools -> Network Tools -> Netstat

----------
2013.6.13

Added Tools -> Network Tools -> Disable Firewall
Added Tools -> Network Tools -> Enable Remote Desktop

----------
2013.6.11

Added Tools -> Application Tools -> Get Browser Version

----------
2013.5.29

Added Tools -> System Tools -> Update Group Policy (gpupdate /force)

----------
2013.5.10

Added AD user info to prompt when disabling user account
Added Tools -> User Tools -> Get User's AD Info

----------
2013.5.2

Added TelephonyTools Class
Added Tools -> Testing -> SubnetPcmServerUpdater in Menu
Added functionality to update Shoretel DVM IP in PCMs subnet wide

----------
2013.4.26

Added Tools -> User Tools -> GetSamAccountName and matching method.
Added Tools -> User Tools -> GetFullName and matching method.
Added Full Name to title bar of window returned by Tools -> User Tools -> Show AD Groups

----------
2013.4.2

Added tolerance for profiles ending in .DOMAIN.
Improved tolerance for PCNAMES starting with backslashes.

----------
2013.3.27

Changed OST printouts to list instead of Message Boxes.
Added Help -> Changelog.

----------

Friday, October 25, 2013