question

RogerRoger-2394 avatar image
0 Votes"
RogerRoger-2394 asked LimitlessTechnology-2700 answered

Remove users from AD group

Hi All

I have a requirement to remove 300 users from an AD group, i have csv file in the below format which contains Userprincipalnames

upn
user1@mydomain.com
user2@mydomain.com

is the below syntax correct.

 import-csv c:\temp\input.csv |
 Foreach-Object{
 $GetSam = Get-ADUser -Filter "UserPrincipalName -eq '$($_.upn)'"
 if ($GetSam){
 Remove-ADGroupMember -Identity "group1" -Members $GetSam.SamAccountName -confirm:$false
 } else {
 Write-Host "$($_.upn) not found in AD"
 }
 }
windows-server-powershellwindows-active-directorywindows-server-2019windows-server-2016
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered Thameur-BOURBITA commented

Here's another version of the code submitted by @Thameur-BOURBITA :

 $Group = 'Group1'
 Import-Csv -path c:\temp\input.csv |
     ForEach-Object{
         $UPN = $_.upn       # needed for "Catch" block
         $samaccountname = Get-ADUser -Filter "UserPrincipalName -eq '$UPN'" -Erroraction SilentlyContinue | 
                                 Select-Object –ExpandProperty Samaccountname
         if ($samaccount){
             Try{
                 Remove-ADGroupMember -Identity $Group1 -Members $SamAccountName -confirm:$false -Erroraction stop
                 Add-content -path c:\temp\_.log -value "$UPN has been removed successfully from $Group"
             }
             Catch{
                 Add-content -path c:\temp\_.log -value "$UPN was not removed from group '$Group' -- ERROR $_"
             }
         }
         else{
             Add-content -path c:\temp\_.log -value "$UPN was not found"               
         }
     }
 Add-content -path c:\temp\_.log -value "---END---"
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Hi,

This filter can't working with this syntax "UserPrincipalName -eq '$UPN'"

All my script are working with syntax 'UserPrincipalName -eq "$UPN"'

Th rest of you code seems ok , nice job.

0 Votes 0 ·

I think you need to reexamine those filter strings!

 # try filter with strings
 get-aduser -Filter 'UserPrincipalName -eq GHI@athome.com'    # Error parsing query: 'UserPrincipalName -eq GHI' Error Message: 'syntax error' <==NO quotes around target
 get-aduser -Filter 'UserPrincipalName -eq "GHI@athome.com"'  # this works (double-quoted string as argument inside single-quoted filter string)
 get-aduser -Filter "UserPrincipalName -eq 'GHI@athome.com'"  # this works (single-quoted string as argument inside double-quoted filter string)
    
 # try filter with variable instead of string
 $UPN = 'GHI@athome.com'
 get-aduser -Filter 'UserPrincipalName -eq "$UPN"'                   # returns nothing (no variable interpolation due to single-quoted filter string)
 get-aduser -Filter "UserPrincipalName -eq '$UPN'"                   # returns user object (single-quoted variable inside double-quoted filter string)
    
 # try filter with no quotes, but "{" "}"
 get-aduser -Filter {UserPrincipalName -eq $UPN}                     # returns user object (no quotes, filter string delimited by "{" and "}")

Check the Get-ADUser help and read the "Note" in the description of the -Filter parameter.

1 Vote 1 ·

I will test it. thank you for your feedback.

0 Votes 0 ·
Thameur-BOURBITA avatar image
0 Votes"
Thameur-BOURBITA answered Thameur-BOURBITA commented

Hi,
You can use this script , it will generate a log file to track all modifications and errors :

 $users = get-content -path c:\temp\input.csv -Delimiter ";"
    
 foreach($user -in $users)
 {
    
 $UPN = $user.upn
 try
 {
 $samaccountname = get-aduser -Filter 'UserPrincipaleName -eq "$UPN" ' -Erroraction stop | select –ExpandProperty Samaccountname
 Remove-ADGroupMember -Identity "group1" -Members $SamAccountName -confirm:$false -Erroraction stop
    
 Add-content -path "c:\temp\_.log" -value "$samaccountname has been removed successfully from group1"
 }
    
 catch
 {
    
 Add-content -path "c:\temp\_.log" -value "$UPN ERROR $_"
 }
    
 }
    
 Add-content -path "c:\temp\_.log" -value "---END---"

Please don't forget to mark heplfull reply as answer

· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Because you're using filter to find the user, the script should never detect a failure to find the user. That's because an unsuccessful search won't generate an exception (even a non-terminating one), and a $null result from the Get-ADUser (or any other $null value) won't be passed into the pipe.

The only error that will be recorded would be if the user was found and the Remove-ADGroupMember failed.

1 Vote 1 ·

If the command get-aduser with the filter doesn't detect any user , the error will be generated by remove-adgroupmember.

0 Votes 0 ·

That's true. But the information written to the log file won't include the sAMAccountName because it's null.

The OP said he was using a CSV, but your code treats the file as a plain text file. It then goes on to use "$user.UPN", but there is no UPN property in a string.

The filter string in your code is also incorrect: 'UserPrincipaleName -eq "$UPN" ' . The quoting is wrong, and the UserPrincipalName is misspelled as "UserPrincipaleName ". Because of the incorrect quoting there will be no interpolation of the variable $UPN -- it will be treated as if "$UPN" is the value.

I've used your code (corrected) to post a new answer.

0 Votes 0 ·
Show more comments
LimitlessTechnology-2700 avatar image
0 Votes"
LimitlessTechnology-2700 answered

Hello RogerRoger

It looks alright, but usually I am using a simple TXT file as this:

Import-Module Activedirectory
$Users = Import-Csv "ListOfUsers.csv" -Header users
ForEach ($User In $Users)
{
$Email = $User.users
# Retrieve the sAMAccountName of the user with the specified email address in the CSV file.
$SamName = (Get-ADUser -Filter {EmailAddress -eq $Email}).sAMAccountName
# Make sure there is just one user found.
Switch ($SamName.Count)
{
0 {Write-Host "User with EmailAddress $Email not found"}
1 {Remove-ADGroupMember -Identity "GroupName" -Members $SamName}
Default {Write-Host "More than one user found with EmailAddress $Email"}
}
}

Reference: https://social.technet.microsoft.com/Forums/en-US/f6b705b9-ed47-4412-beaf-9ff7d8ed8b65/removing-list-of-users-from-ad-group?forum=winserverDS



--If the reply is helpful, please Upvote and Accept as answer--

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.