Home > Software engineering >  Get-ADUser - Filter child OU's and users where surname is empty
Get-ADUser - Filter child OU's and users where surname is empty

Time:11-25

I am trying to run a command where I get all active directory users in the parent OU (Users) and filter out the child OU's (Admin accounts, service accounts, disabled accounts) as well as filter out any user account that does not have a surname in the surname field.

At the moment I have

Get-ADUser -Filter{enabled -eq $true} -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' | Where-Object { $_.DistinguishedName -notlike "*,$Disabled" } | Where {$_.Surname -notlike "$Null"} | select samAccountName

When I add another child OU after 'Disabled' there is an error

Where-Object : A positional parameter cannot be found that accepts argument 'Where'.

Please may someone advise on how to filter out additional child OU's?

CodePudding user response:

Good day Smoore

The problem is you are using multiple Where-object cmdlets but you only need one and separate them using () and adding the -and option, also to refer to $null value you don't need to use the "" marks

Get-ADUser -Filter {Enabled -eq $true} -SearchBase "OU=Users,OU=Company,DC=CompanyName,DC=local" | Where-Object {($_.DistinguishedName -notlike "*,$Disabled*") -and ($_.Surname -notlike $Null)} | select samAccountName

With this options you should be able to get all the users you want

Have a nice day!

CodePudding user response:

I would use a regex -notmatch so it would be possible to combine all OU Distinguished names in just one variable.

Something like this:

$Admins   = 'OU=Administrators,OU=Company,DC=CompanyName,DC=local'
$Service  = 'OU=ServiceAccounts,OU=Company,DC=CompanyName,DC=local'
$Disabled = 'OU=DisabledUsers,OU=Company,DC=CompanyName,DC=local'

# build a regex string from the above OU DistinguishedNames
$Exclude = '({0}|{1}|{2})$' -f [regex]::Escape($Admins), [regex]::Escape($Service), [regex]::Escape($Disabled)

Get-ADUser -Filter 'Enabled -eq $true' -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' | 
Where-Object { ![string]::IsNullOrWhiteSpace($_.Surname) -and $_.DistinguishedName -notmatch $Exclude } | 
Select-Object SamAccountName
  • Related