Link to home
Start Free TrialLog in
Avatar of Alex
AlexFlag for United Kingdom of Great Britain and Northern Ireland

asked on

powershell syntax help

$group1 = "***-***-S-U ZScaler Pilot" 
$Users = get-content 'C:\Powershell Projects\Get-viuser\user.txt'
Foreach ($user in $users) {
        Get-ADUser -identity $user -Properties memberof | where-object {$_.memberOf -notcontains $group1

Open in new window


Can anyone tell me why this doesn't work?

Thanks
Alex
Avatar of Sajen Jose
Sajen Jose
Flag of India image

Hi Alex

What is the error you are getting?

you may want to try this line for the Get-ADUser cmdlet.

Get-ADUser -identity $user -Properties memberof | where-object {!($_.memberof -like $group1)}
Avatar of Alex

ASKER

It was still pulling people with the group added, I want people without the group.
okay... you may want to try the FQDN for the group and give it a shot, remember reading somewhere that the wild chars may have issues...
Avatar of Alex

ASKER

I've put it in using the samaccountname too and that doesn't work either :S
Hi Alex,

I tried in my lab environment by creating a group called SJGroup and giving the full DN and searching for the users that belong to this group and it came out fine.

I think in your case you want to exclude the users containing the group, you can probably handle it at the  if condition.

I agree not a pretty script, but it seems to be working at my end :)

$excgroup = "CN=SJGroup,CN=Users,DC=Demo2,DC=LEL"

$mysers = Get-Content "C:\Users\Admin\Desktop\users.txt"

foreach ($user in $myusers)
{
	$userdetails = Get-ADuser -Identity $user -Properties memberOf
	
	foreach ($entry in $userdetails.memberOf)
	{
		If ($excgroup -contains $entry)
		{
			Write-Host $userdetails.SamAccountName
		}
	}
}

Open in new window

Note: $mysers  - the variable name should be $myusers  typo :)
Avatar of Alex

ASKER

Pretty is irrelevant as long as it works mate,

Trying it now.

Thanks
Alex
Avatar of Alex

ASKER

Doesn't seem to work, it's giving me users with the group.
Your original code should work if you supply the distinguishedname for the group.  The -contains and -notcontains operators don't do partial matches against an array/collection.  To get a match your search term has to be present (in totality) as an element of the array.  And since the memberOf attribute is an array of distinguishednames...(gotobeginning)
ASKER CERTIFIED SOLUTION
Avatar of Alex
Alex
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Alex

ASKER

This was the only way to get it to work