Basic array queries

by cycoburns at 2013-02-28 13:44:18

I’ve hit a mental block here…I’m sure this should work, but it’s not. I’ve created a variable and used get-aduser to populate it, straight forward.

PS Child:> [Array]$ExistingUserDetails = Get-AdUser $username -Properties GivenName,SurName,EmailAddress,Office,Title
PS Child:> $existinguserdetails

DistinguishedName : CN=blah,OU=blah,OU=blah,OU=blah,DC=blah,DC=blah,DC=blah
EmailAddress :
Enabled : True
GivenName : John
Name : John Smith
ObjectClass : user
ObjectGUID : xxxxxxxx
Office : OfficeLocation
SamAccountName : JSmith
SID : S-1-1-1-11111111-1111111-111111111-11111
Surname : Smith
Title : Squire
UserPrincipalName : JSmith@blah.blah.blah

However, when trying to call particular pieces of information, such as givenname, I get nothing:

PS Child:> $existinguserdetails.surname
PS Child:> $existinguserdetails.givenname

I thought i could query the array like this, and it should jsut return “John”. What I am getting inside my script when I query $existinguserdetails, is just the first line returned, the “DistinguishedName” value only.
Literally if I do a “write-host $existinguserdetails”, I get one line only. Even though when I manually run the commands it returns the 13 lines.

by DonJ at 2013-02-28 13:59:52
So… that’s because you created an array. You have to tell it which array element you want. Since there’s likely only one, $existinguserdetails[0].surname should work.

One doesn’t “query” an array. You just access data in it. Querying implies it’s going to search something for you, and it ain’t.

Curious: Why are you casting it as an array? Get-ADUser will return a single object if there’s only one match, and return a collection (array) if there’s more than one match. Do you need to force it into an array?