Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Problems removing a user from a Group where the group dn contains a "/" character

$
0
0

Hellos.

We have a requirement that when a User's contract (leaves company) his AD account is Disabled and All Group memberships are removed.

The Powershell script running to do this contains theses lines:-

$id is samaccountname of user to have his group memberships nullified

$PPSServer is FQN of AD domain controller

$ErrorActionPreference  = "stop"
$Error.Clear()

$strFilter = "(&(objectCategory=person)(objectClass=user)(samAccountName=$id))"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://"+$PSServer) 

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$objSearcher.PropertiesToLoad.Add('memberOf')

$dn = $objSearcher.findOne()
if ($dn -eq $null -or $dn.count -eq 0) {
$x= "No user found with username=" + $id
$x
exit
}

# set his description attribute on AD
$datestr = Get-Date -format "dd.MM.yyyy"
$desc = "Disabled " + $datestr

$MyuserDN = $dn.path
$MyuserObj = [ADSI]$MyuserDN 
$x = $MyuserObj.Put("description",$desc)
$x = $MyuserObj.SetInfo()

$output = ""
$userObj = $dn.GetDirectoryEntry()
$userDN = $userObj.distinguishedName.Value
$groups = $userObj.memberOf

if ($groups -eq $null -or $groups.count -eq 0)
{
   $x = $userDN + " has no AD group memberships" + "`r`n"
   $x
}
else
{
   foreach ($groupDN in $groups)
   {
$grpEnt = New-Object System.DirectoryServices.DirectoryEntry("LDAP://"+$groupDN)
$output = $output + " Removing user: " + $userDN + " from group: " + $groupDN + "`r`n"
$grpEnt.Properties["member"].Remove($userDN);
    $grpEnt.CommitChanges();
    $grpEnt.Close();
   }
}
$output
#debug/logging
# get the Groups he is currently a member of now
#$x=Get-ADPrincipalGroupMembership -Identity $id
#$x

If the $groupDN contains a / then I get error "Cannot index into a null array." when the command $grpEnt.Properties["member"].Remove($userDN); is executed.

WHY???????

To keep me going I have simply added $ErrorActionPreference  = "SilentlyContinue" before the foreach loop. But I really want to know what is causing this error. 


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>