Vik
Vik

Reputation: 167

How can I extract multiple attributes of manager in AD using Powershell?

I have a one line powershell command to extract managers from active directory, but it only gives me one attribute. What can I do to get more attributes like name, sAMAccountName and employeeNumber.

The command below just gives the employeeNumber of manager.

Get-ADUser -Filter * -SearchBase "OU=Users,OU=Office365,DC=example,DC=lan" -Properties * | Select-Object name, employeeNumber, @{Name='Manager';Expression={(Get-ADUser -Property employeeNumber $_.Manager).employeeNumber}} | export-csv -path c:\temp\userexport.csv

Desired csv file headers:

name    employeeNumber   ManagerName      ManagerEmployeeNumber

Upvotes: 1

Views: 761

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

If you are attempting to store multiple values in a single cell of a CSV file, you will have to create a delimited list within that cell.

# Calculated property joining property values with ;
# Use try-catch because some users may not have a manager
# No manager will throw a [ParameterBindingValidationException] exception.
$ManagerProp = @{
    Name='Manager'
    Expression={
        try {
            $user = Get-ADUser $_.Manager -Properties EmployeeNumber
            "{0};{1};{2}" -f $user.Name,$user.SamAccountName,$user.EmployeeNumber
        }
        catch { }
    }
}
Get-ADUser -Filter * -SearchBase "OU=Users,OU=Office365,DC=example,DC=lan" -Properties EmployeeNumber,Manager |
    Select-Object Name,EmployeeNumber,$ManagerProp |
        Export-Csv -Path c:\temp\userexport.csv -NoType

-f is the String format operator.

Note that it is not efficient to use -Properties * because of the overhead required to retrieve unneeded properties.


You could give each Manager property its own property:

Get-ADUser -Filter * -SearchBase "OU=Users,OU=Office365,DC=example,DC=lan" -Properties EmployeeNumber,Manager |
    Foreach-Object {
        $obj = [pscustomobject]@{
            Name = $_.Name
            EmployeeNumber = $_.EmployeeNumber
            Manager_Name = ''
            Manager_SamAccountName = ''
            Manager_EmployeeNumber = ''
        }
        if ($_.Manager) {
            $Manager = Get-ADUser $_.Manager -Properties EmployeeNumber
            $obj.Manager_Name = $Manager.Name
            $obj.Manager_SamAccountName = $Manager.SamAccountName
            $obj.Manager_EmployeeNumber = $Manager.EmployeeNumber
        }
        $obj
        }
    } | Export-Csv -Path c:\temp\userexport.csv -NoType
                           

Upvotes: 2

Related Questions