Dive Into PowerShell: Part 2 – Backpacking

Today I found a great PowerShell script posted by Raymund Macaalay, so I decided to write this post on the importance of community learning.  The script was an answer to a Stack Overflow question on how to remove a large set of users from a domain, with each user having their own active directory.  Doing this manually would be a waste of time and why not make a simple script that can do it for you.  Online communities are great for this reason, you randomly learn new things constantly.

There are too many types of online communities to cover them all but, Stack Overflow, Reddit, IBM’s DeveloperWorks, Effbot, and individual developers are good sources of information.  Also you can never go wrong with mailing lists.

Raymund Macaalay’s Information:

Blog – AnyRest: http://anyrest.wordpress.com/

SO Profile: http://stackoverflow.com/users/412519/raymund

SO Post: http://stackoverflow.com/questions/9379922/remove-all-ex-employees-from-all-distribution-groups

Raymund’s PowerShell Script

Add-Type -AssemblyName System.DirectoryServices.AccountManagement

$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher
$directorySearcher.SearchRoot = "LDAP://OU=YourOU,DC=YourDomain,DC=com"
$directorySearcher.PageSize = 1000
$directorySearcher.Filter = "(&(objectCategory=User))"
$directorySearcher.SearchScope = "Subtree"
$directorySearcher.PropertiesToLoad.Add("name")
$searchResults = $directorySearcher.FindAll()

foreach ($result in $searchResults)
{$objItem = $result.Properties
"Name: " + $objItem.name

$contextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$userPrincipal = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($contextType,$objItem.name)
$userGroups = $userPrincipal.GetGroups()

foreach($userGroup in $userGroups)
{
if ($userGroup.IsSecurityGroup -eq 0) #Distribution Group Only
{
"Removing - " + $userGroup.SamAccountName
$userGroup.Members.Remove($userPrincipal)
$userGroup.Save()
}
}
}

Raymund’s .Net Script

using System;
using System.Collections;
using System.Linq; using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

namespace RemoveFromDistributionGroups
{
class Program
{
private static string sDomain;
private static string sDefaultOU;
private static string sServiceUser;
private static string sServicePassword;

static void Main(string[] args)
{
try
{
Console.Write("Type your Domain (i.e: yourcompany.com) ");
sDomain = Console.ReadLine();

Console.Write("Type the OU you want to use: (i.e: OU=yourou,DC=yourcompany,DC=com)");
sDefaultOU = Console.ReadLine(); Console.Write(@"Username: (i.e.: YOURDOMAIN\Raymund )");

sServiceUser = Console.ReadLine();
Console.Write("Password: ");

sServicePassword = Console.ReadLine();

foreach (UserPrincipal user in GetAllUsers())
{
Console.WriteLine("Processing User : " + user.Name);
foreach (GroupPrincipal group in GetUserGroups(user))
{
if (group.IsSecurityGroup == false) //Distribution Group
{
group.Members.Remove(user);
group.Save();
}
}
}
Console.WriteLine("Done! Press a key to exit");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Error Encountered : " + ex.Message);
Console.WriteLine("Press a key to exit");
Console.ReadLine();
}
}

public static PrincipalContext GetPrincipalContext(string sOU)
{
PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, sDomain, sOU, ContextOptions.Negotiate, sServiceUser, sServicePassword);

return oPrincipalContext;
}

public static ArrayList GetAllUsers()
{
ArrayList myItems = new ArrayList();
PrincipalSearcher oPrincipalSearcher = new PrincipalSearcher();
UserPrincipal oUserPrincipal = new UserPrincipal(GetPrincipalContext(sDefaultOU));
oUserPrincipal.SamAccountName = "*";
oUserPrincipal.Enabled = true;
 oPrincipalSearcher.QueryFilter = oUserPrincipal;
((DirectorySearcher)oPrincipalSearcher.GetUnderlyingSearcher()).PageSize = 5000;
PrincipalSearchResult<Principal> oPrincipalSearchResults = oPrincipalSearcher.FindAll();

foreach (Principal oResult in oPrincipalSearchResults)
{
myItems.Add(oResult);
}

return myItems;
}

public static ArrayList GetUserGroups(UserPrincipal oUserPrincipal)
{
ArrayList myItems = new ArrayList();
PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();

foreach (Principal oResult in oPrincipalSearchResult)
{
myItems.Add(oResult);
}

return myItems;
}
}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s