The following worked for me.
Note: I got the .csv from the Entra admin panel. Entra gave me the .csv with the column named "Id" instead of "userID". All examples I found had the script referencing "userID".
To use this script, the column on your CSV must be named "Id"
# Connect to Microsoft Graph
Connect-MgGraph -Scopes "User.ReadWrite.All", "Directory.ReadWrite.All"
# Import the CSV file
$csv = Import-Csv -Path 'REPLACE WITH PATH TO YOUR CSV'
# Retrieve all users
$allUsers = Get-MgUser -All
# Iterate through each row in the CSV file
foreach ($row in $csv) {
if (![string]::IsNullOrEmpty($row.id)) {
# Retrieve the current manager of the user
$currentManager = Get-MgUserManager -UserId $row.id -ErrorAction SilentlyContinue
if ($currentManager) {
Write-Host "User $($row.id) already has a manager assigned. Skipping..."
} else {
# Retrieve the manager's ID based on the display name
$manager = $allUsers | Where-Object { $_.displayName -eq $row.managerDisplayName }
if ($manager) {
$NewManager = @{
'@odata.id' = "https://graph.microsoft.com/v1.0/users/$($manager.Id)"
}
# Update the user's manager
Set-MgUserManagerByRef -UserId $row.id -BodyParameter $NewManager
} else {
Write-Host "Manager with display name $($row.managerDisplayName) not found."
}
}
} else {
Write-Host "UserId is empty for one of the rows. Skipping..."
}
}