Home > database >  A Script that pulls list of AD users and returns manager info
A Script that pulls list of AD users and returns manager info

Time:07-08

I'm working on script to pull the users' name, email address, and their manager info. I need some help. I have this so far

$requestedUsers = Import-Csv "ADUserlist.csv"

$allUsers = Get-ADUser -filter 'Enabled -eq $true' -Properties name, EmailAddress, Manager

$filterdUsers = $allUsers | Where-Object { $_.SamAccountName -in$requestedUsers.SamAccountName }

 $report = foreach ($user in $filterdUsers) {
$managerEmail = $allUsers |
Where-Object DistinguishedName -eq $user.Manager |
Select-Object -ExpandProperty EmailAddress

[PSCustomObject][ordered]@{
    DisplayName  = $user.Name
    EmailAddress = $user.EmailAddress

    ManagerEmail = $managerEmail
}
 }

 $report | Out-GridView

there is no output I don't know where exactly I made a mistake. So I need help if there is any changes to be made.

CodePudding user response:

It should be something like this

Import-Module -name 'ActiveDirectory'

$requestedUsers = Import-Csv -path "ADUserlist.csv" #Full path required

$allUsers = Get-ADUser -filter 'Enabled -eq $true' -Properties 'name', 'EmailAddress', 'Manager'

$filterdUsers = $allUsers | Where-Object { $_.SamAccountName -in $requestedUsers.SamAccountName }

$report = @()

foreach ( $user in $filterdUsers ) {
    $managerEmail = ( $allUsers | Where-Object { $_.DistinguishedName -eq $user.Manager } ).EmailAddress

    $PSO = [PSCustomObject]@{
        DisplayName  = $user.Name
        EmailAddress = $user.EmailAddress
        ManagerEmail = $managerEmail
    }

    $report  = $PSO
}

$report | Out-GridView

If you run this script on AD controller, first you must import module ActiveDirectory.
If you run this script on non AD controller you must use powershell remoting to connect to AD controller and run the script. And of course you must have privilege to run such scripts.

  • Related