Author Posts

September 23, 2016 at 3:08 pm

I'm trying to determine what the members are of an AD group, I know we can only have users, groups or contacts to these groups.

I was trying something like:

if (Get-ADUser $member -erroraction silentlycontinue)	
{
	"user"
}
elseif (Get-ADGroup $member -erroraction silentlycontinue)
{
	"group"
}
else
{
	"contact"
	(Get-ADObject -LDAPFilter "ObjectClass=Contact" | Where-Object{ $_.distinguishedName -like $member }).name
}

I guess my thoughts were it would do the first If, and if that command failed, silently continue to the elseif...but that just generates an error like:

Get-ADUser : Cannot find an object with identity: 'CN=contact so-andso,OU=Contacts,DC=domain,DC=com' under:
'DC=domain,DC=com'.
At line:3 char:6

How would I go about doing something like this?

September 23, 2016 at 3:48 pm

The Get-AD* cmdlets, in my experience, require the use of a try-catch statement. ErrorAction, with any parameter value, simply doesn't work. Try the difference between

try {
    Get-ADUser -Identity $member
} catch {
    Write-Warning -Message 'Unable to locate object in Active Directory.'}

when $member is set to an actual object, and when it's not.

Edit: Added pre tags.

  • This reply was modified 1 year, 12 months ago by  tommymaynard.
  • This reply was modified 1 year, 12 months ago by  tommymaynard.
  • This reply was modified 1 year, 12 months ago by  tommymaynard.
  • This reply was modified 1 year, 12 months ago by  tommymaynard.

September 23, 2016 at 3:53 pm

I did originally have it as a try catch, but then i remembered it had a 3rd statement and wasnt sure how to use it..

try
{
        Get-ADUser $member -erroraction stop
	"user"
}
catch
{
	get-adgroup $member -erroraction stop
        "group"

        #not sure how to incorporate the 3rd one here as it will stop on the group fail
	"contact"
	(Get-ADObject -LDAPFilter "ObjectClass=Contact" | Where-Object{ $_.distinguishedName -like $member }).name
}

September 23, 2016 at 5:54 pm

Use the filter if you don't want a terminating error.

Get-AdUser -Filter "SamAccountName -eq 'someone'"

September 23, 2016 at 9:22 pm

Why not just used Get-ADObject and check the objectclass?

$members = "CN=testcontact,DC=domain,DC=local","CN=testgroup,DC=domain,DC=local","CN=testuser,DC=domain,DC=local"

$members | 
ForEach-Object {
    "$_ is a: $(Get-ADObject -Identity $_  -Properties objectclass | Select-Object -ExpandProperty ObjectClass)"
}

Results:

CN=testcontact,DC=domain,DC=local is a: contact
CN=testgroup,DC=domain,DC=local is a: group
CN=testuser,DC=domain,DC=local is a: user