2

The ADSI query works fine, it returns multiple users.

I want to select the 'name' and 'email' from each object that is returned.

$objSearcher = [adsisearcher] "()"
$objSearcher.searchRoot = [adsi]"LDAP://dc=admin,dc=domain,dc=co,dc=uk"
$objSearcher.Filter = "(sn=Smith)"
$ADSearchResults = $objSearcher.FindAll()

$SelectedValues = $ADSearchResults | ForEach-Object { $_.properties | Select -property mail, name }

$ADSearchResults.properties.mail gives me the email address

When I omit the 'select -properties' it will return all the properties, but trying to select certain properties comes back with nothing but empty values.

beehaus
  • 415
  • 1
  • 4
  • 13
  • 1
    If you're not stuck on Windows XP, I encourage you to use `Get-ADUser` from the `ActiveDirectory` PowerShell module that's a part of [RSAT](http://blogs.msdn.com/b/rkramesh/archive/2012/01/17/how-to-add-active-directory-module-in-powershell-in-windows-7.aspx). – Bacon Bits Apr 21 '15 at 14:36

2 Answers2

3

Whenever working with ADSI I find it easier to expand the objects returned using .GetDirectoryEntry()

$ADSearchResults.GetDirectoryEntry() | ForEach-Object{
    $_.Name
    $_.Mail
}

Note: that doing it this way gives you access to the actual object. So it is possible to change these values and complete the changes with something like $_.SetInfo(). That was meant to be a warning but would not cause issues simply reading values.

Heed the comment from Bacon Bits as well from his removed answer. You should use Get-Aduser if it is available and you are using Active Directory.

Update from comments

Part of the issue is that all of these properties are not string but System.DirectoryServices.PropertyValueCollections. We need to get that data out into a custom object maybe? Lets have a try with this.

$SelectedValues = $ADSearchResults.GetDirectoryEntry() | ForEach-Object{
    New-Object -TypeName PSCustomObject -Property @{
        Name = $_.Name.ToString()
        Mail = $_.Mail.ToString()
    }
}

This simple approach uses each objects toString() method to break the data out of the object. Note that while this works for these properties be careful using if for other and it might not display the correct results. Experiment and Debug!

Matt
  • 45,022
  • 8
  • 78
  • 119
  • Thanks Matt, the DirectoryEntry() method works, it returns all the values to the screen, the difficulty I am having is I wanted $SelectedValues to be an object holding all the 'mail' and 'name' values for all the 'Smiths' it found in the directory – beehaus Apr 21 '15 at 14:54
  • Thanks again @Matt, that works good :) just what I was looking for. Think I understand the answer ... getting my head around .NET objects and methods is quite a challange – beehaus Apr 21 '15 at 16:07
2

Have you tried adding the properties?

$objSearcher.PropertiesToLoad.Add("mail")
$objSearcher.PropertiesToLoad.Add("name")
MonkeyDreamzzz
  • 3,978
  • 1
  • 39
  • 36