-Like, -Match in subarray

518 Views Asked by At

I am working on getting a list of inactive users from Active Directory with Search-ADAccount then piping that to Get-ADUser so I can use where MemberOf does not contain the group "Accounts_to_Keep". I believe I have it working with the correct number (379) with the full DN string. In case the group moves, though, I would like to use -match or -like to just use the name of the group. The number it returns is not the same.

If I do this individually on a single user with MemberOf it just filters out the one group and returns the other the user has so I think this is why I have more than the -contains. Is there a way to use -like or -match for the subarray without foreaching it myself?

Full DN removed from string

PS> $InactiveAll.Count
488
PS> ($InactiveAll | Where {-not $_.memberof.contains("CN=Accounts_to_Keep,OU=DC")}).Count 
379
PS> ($InactiveAll | Where { $_.memberof -notlike "*Accounts_To_keep*"}).Count 
427
PS> ($InactiveAll | Where {-not $_.memberof -contains ("CN=Accounts_to_Keep,OU=DC")}).Count 
61
PS> ($InactiveAll | Where {-not ($_.memberof -contains ("CN=Accounts_to_Keep,OU=DC"))}).Count
379
PS> ($InactiveAll | Where { $_.memberof -notmatch "Accounts_To_Keep"}).Count
427
2

There are 2 best solutions below

0
On BEST ANSWER

-like and -notlike use wildcards, "*". Also using -notlike and -notmatch on an array of groups have a different result than using them on single elements. I think you need to research what these operators do. Any result will evaluate to "true" in where-object.

'group1','group2','group3' -notmatch 'group1'
group2
group3


'group1','group2','group3' -notlike '*group1*'
group2
group3

Here's a way to search for substrings in an array of strings:

| where { -not ($_.memberof | select-string group1) }

Or

| where { -not ($_.memberof -match 'group1') }
| where { -not ($_.memberof -like '*group1*') }
1
On

I don't think -match would offer any advantage over -like for testing distinguished names since, in this case, you know 'CN=Accounts_to_Keep' will identify the desired group by name. Don't forget that -notcontains exists to simplify your code a little bit.

This code might be a little off since I don't have a directory in front me to test against, but if you want to exclude members of that group wherever it may exist I think you should let Active Directory handle finding the group...

$groupToExclude = Get-ADGroup -Identity 'Accounts_to_Keep'

...and then instead of matching distinguished name substrings you can match the distinguished name as a whole...

($InactiveAll | Where { $_.MemberOf -notcontains $groupToExclude.DistinguishedName}).Count

This assumes there is only one group in the domain named Accounts_to_Keep. If that cannot be guaranteed, instead of its name you could pass that group's objectGUID or objectSid to Get-ADGroup to retrieve that exact group with no ambiguity.