Confirm when account was removed from group with PS

can someone help me modify this so when an account that is in the users.txt file is not in the group , it will output an error that specifies the samaccountname that was not in the group ?

Instead of the generic error

Remove-ADGroupmember : The specified account name is not a member of the group
At C:\removefromgroups.ps1:3 char:1
+ Remove-ADGroupmember -identity $_ -member $User -Confirm:$false
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (MY Test group:ADGroup)

Foreach ($User in GC C:\Users.txt){
GC C:\groups.txt | % {
Remove-ADGroupmember -identity $_ -member $User -Confirm:$false
      }
}

Open in new window

LVL 2
MilesLoganAsked:
Who is Participating?
 
Jose Gabriel Ortega CConnect With a Mentor CEO J0rt3g4 Consulting ServicesCommented:
As footech says:

Foreach ($User in GC C:\Users.txt){
GC C:\groups.txt | % {
    try{
        Remove-ADGroupmember -identity $_ -member $User -Confirm:$false -ea stop
    }
    catch{
        $error=$_.exception.ErrorMessage
        write-output "The user with samAccountName: $_  was not in the group. ErrorMessage:$error" 
    }
      }
}

Open in new window

0
 
footechCommented:
I don't remember hearing about any change in behavior around this cmdlet, but on a couple machines I've tested specifying a user that isn't a member of the group doesn't produce any error.
I've only tested on PS versions 5.0 and 5.1.

Typically I would expect to have to deal with such an exception by using a Try/Catch statement, and it might require the Remove-ADGroupMember cmdlet to have the -ErrorAction parameter set to Stop so that the error becomes terminating.
1
 
Daryl BamforthTechnical ExpertCommented:
The catch for that error is


catch [Microsoft.ActiveDirectory.Management.ADException] {

}

Open in new window


You can find the exception by using
catch {
    write-output "Unexpected Exception: $($error[0].Exception.GetType().Fullname)"
    $UnexpectedException = $error[0].Exception.GetType().Fullname

}

Open in new window


Ideally every exception should be handled correctly, if you add the above as a final catch you will be able to build up your scripts to handle any eventuality.
0
 
MilesLoganAuthor Commented:
Thank you Jose , that is what I was looking for .
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.