Pages

3/27/2011

Powershell: Import Group Members

This script will be used to import a file of the same format that I export from the previous post. After using Excel to review and change the listings. I use these group memberships to filter group policy permissions to apply WSUS client settings to servers.

############################################################################
#
# IMPORT-SERVER-GROUP.PS1
#
# Assign servers to WSUS group from CSV file.  
# Note:  removes server from any existing groups that contain WSUS
#
# CSV Format:  (include headings)
#
#  Server, Group
#  SERVER01, WSUS Test Group
#
############################################################################

$list = @(Import-Csv WSUS-TEST.CSV)
$today = get-date

"==========================================================================="
" CHANGE LOG - " + $today

foreach ( $item in $list ) {
 $account = $item.Server;
 $target = $item.Group;

"---------------------------------------------------------------------------"
 "    " + $account

#Find computer object and remove it from groups
 $ds = new-object directoryServices.directorySearcher 
 $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$account))" 
 $dn = $ds.findOne() 
 if ($dn) { #found
  #remove computer from groups
  $user = [ADSI]$dn.path 
  "      Removed from groups:"
  foreach ($group in $user.memberof)
   {
   $groupDE = [ADSI]"LDAP://$group" 
   "        "+$group
   if ($strGroup -match "WSUS") {
    $groupDE.remove("LDAP://$($user.distinguishedName)")  
    }#if
   }#foreach
 }#if

$dn=0;

#Find group object and add server to it
 $ds = new-object directoryServices.directorySearcher 
 $ds.filter = "(&(objectClass=Group)(name=$target))" 
 $dn = $ds.findOne() 
 if ($dn) { #found Group
  $group = [ADSI]$dn.path 
  $groupDE = [ADSI]"LDAP://$($group.distinguishedname)" 
  $ds.filter = "(&(objectCategory=computer)(objectClass=user)(name=$account))" 
  $dn = $ds.findOne()
  if ($dn) { #found machine account
   $usr = [ADSI]$dn.path
   $ADuser = [ADSI]"LDAP://$($usr.distinguishedname)"
   "      Added to " + $target
   $groupDE.add("LDAP://$($ADuser.distinguishedName)")  
   }#if
 }#if
}#foreach
"==========================================================================="
############################################################################

No comments: