Powershell check user in group and then add if not a member

Watts, Steven 0 Reputation points


The script below keeps dropping into the 'Automation has failed...' else statement once a user has been added into a security group. I can see that the user has been added but need the additional check to write the output as these outputs are being used in a workflow in ServiceNow to determine the next action to be taken.

I'm not a windows administrator and don't use PS that often but the logic looks sound to me. Wondering if I need to 'wait' a certain amount of time to do the additional check to give the domain controllers chance to replicate? Hench it coming back as a failure?

Appreciate any assistance.

# Get the user and group information
$user = get-aduser $UserName -server $UserController -credential $MyCredentials
$group = get-adgroup $GroupName -server $DomainController -credential $MyCredentials
$members = Get-ADGroupMember -server $DomainController -credential $MyCredentials -Identity $GroupName -Recursive |Select -ExpandProperty distinguishedName

# Check group membership

If ($members -contains $user) {
    Write-Host("User exists in the group")
    Set-ADObject -identity $group -add @{member=$user.DistinguishedName} -server $DomainController -credential $MyCredentials	
	If ($members -contains $user) {
    		Write-Host("User successfully added to group")
		Else {
			Write-Host("Automation has failed, user not added to group")
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
1,859 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 43,931 Reputation points

    This line: If ($members -contains $user) {

    Should be: If ($members -contains $user.distinguishedname) {

    0 comments No comments

  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.

    Comments have been turned off. Learn more