批量更改管理器字段的 AzureAD Powershell 脚本

AzureAD Powershell Script to Bulk Change Manager Field

  1. 我的目标是拥有一个 Powershell 脚本,该脚本可以导入 CSV 以批量更改 AzureAD 中的用户管理器字段。 CSV 将有 2 列,一列是用户,另一列是他们的经理。
  2. 我找到了将所有用户从 AzureAD 导出到 CSV 的脚本,但它不包含经理字段的列 header。我找到了一个 AzureAD 脚本,它可以使用 objectID 更改经理字段,但这很麻烦,所以理想情况下我可以为经理字段使用电子邮件地址。
  3. 我没有真正的代码可以展示,这些是我找到的非常基本的脚本,但我充其量只是一个非 Powershell 用户。

Get-AzureADUserManager 和 Set-AzureADUserManager 只接受 ObjectID 作为输入,类似于许多其他 AzureAD cmdlet。

您需要采用多步骤方法来实现结果,以下是我将采取的步骤

  1. 获取所有 Azure AD 用户,例如$AllAzureADUser = Get-AzureADUser -All
  2. 使用计算的 属性 根据您迭代的 ObjectID 用户填充经理字段(本质上这是 Foreach 循环)

$AllAzureADUserWithManager = $AllAzureADUser | select *, @{ Name = "ManagerObjectId"; Expression = { Get-AzureADUserManager $_.ObjectId }}

  1. 现在您在 $AllAzureADUserWithManager 中拥有了做出决策和更新对象所需的所有数据。如果你想使用UPN更新你可以根据UPN查找ObjectId

假设您迭代了一个从 CSV 导入的对象,其中有 targetUserUPNtargetManagerUPN 作为列:

$TargetUserObjectId = $AllAzureADUserWithManager | Where {$_.UPN -eq $row.targetUserUPN} | select -ExpandProperty ObjectId
$TargetManagerObjectId = $AllAzureADUserWithManager | Where {$_.UPN -eq $row.targetManagerUPN} | select -ExpandProperty ObjectId
Set-AzureADUserManager -ObjectId $TargetUserObjectId -RefObjectId $TargetManagerObjectId

如果您每天都需要 运行 考虑使用增量并导出到 csv 之前的 运行 并且如果您有大量用户则过滤到仅需要的内容。

让我们假设您有以下文件:

左边是用户的用户名,右边是新经理的用户名。

您可以使用以下代码段

#connecting to the Azure AD
Connect-AzureAD 

#importing the CSV source which has the changes 
$data = Import-Csv D:\Temp\Book1.csv

#Iterating through each row in the CSV
foreach ($row in $data)
{
#INFO in the Console
Write-Host "Updating the user :"  $row.'User Username'    " manager to "  $row.'Manager Username'  -ForegroundColor Yellow 

#Updating the Manager 
Set-AzureADUserManager -ObjectId (Get-AzureADUser -ObjectId $row.'User Username').Objectid -RefObjectId (Get-AzureADUser -ObjectId $row.'Manager Username').Objectid

#Completion info in the console for the specified row
Write-Host "Updated." -ForegroundColor Green

}

解释:

第 1 步: 连接到 Azure AD

第 2 步: 导入需要批量更新的CSV数据

第 3 步: 遍历每一行,使用 commandlet Set-AzureADUserManager

更新 manager 字段

示例输出: