Search code examples
arrayspowershellobjectselectadsi

Selecting certain properties from an object in PowerShell


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.


Solution

  • 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!