Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerShell to generate report of all AD users with Manager

Please bear with me. I have no experience using AAD/PS.

I am just playing around trying to generate a list of users and their managers.

What I have done is something like this:

$UserId = (Get-AzureADUser -All $true).ObjectId
$bla = foreach ($User in $UserId)
    {
        write-output $User
        Get-AzureADUserManager -ObjectId $User
    }
$bla | Out-File "C:\Temp\Test.txt"

I populate $UserId with a users ObjectId and then search manager for that user user the Get-AzureADUserManager.

How can I change it to generate a list that includes the following data:

UsersObjectId UserUPN UserType ManagersObjectId ManagerUPN ManagerUserType

I also want it to include all UserObjectIds that does not have any manager set (include null).

Any ideas how to achieve this?

like image 521
Andy Thompson Avatar asked Sep 15 '25 09:09

Andy Thompson


1 Answers

This should do what you want:

$output = @()

$users = Get-AzureADUser -All $true

foreach ($user in $users) {
    $manager = Get-AzureADUserManager -ObjectId $user.ObjectId

    $data = New-Object -TypeName psobject

    $data | Add-Member -MemberType NoteProperty -Name UsersObjectId -Value $user.ObjectId
    $data | Add-Member -MemberType NoteProperty -Name UserUPN -Value $user.UserPrincipalName
    $data | Add-Member -MemberType NoteProperty -Name UserType -Value $user.UserType
    $data | Add-Member -MemberType NoteProperty -Name ManagersObjectId -Value $manager.ObjectId
    $data | Add-Member -MemberType NoteProperty -Name ManagerUPN -Value $manager.UserPrincipalName
    $data | Add-Member -MemberType NoteProperty -Name ManagerUserType -Value $manager.UserType

    $output += $data

}

$output | Export-Csv -Path output.csv -NoTypeInformation

It will create a CSV file with columns equal to the data you are looking for, where each row represents a user from the original query.

This also works if Get-AzureADUserManager returns null.

like image 127
Shawn Tabrizi Avatar answered Sep 18 '25 08:09

Shawn Tabrizi