使用以下代码
import-module activedirectory
$users = @("user1", "user2", "user3")
$results = @()
foreach($user in $users) {
$properties = @{
Name = (get-aduser -Identity $user).Name
Manager = get-aduser (get-aduser -Identity $user -Properties manager).manager -properties displayName
DirectReports = get-aduser (Get-ADUser -Identity $user -Properties directreports).directreports -properties displayName
}
$results += New-Object psobject -Property $properties | select Name, Manager, DirectReports
}
$results
只有user3实际上有直接报告,所以它正在打印他的线3次。但它不会为user1和user2打印一行。即使DirectReports列为空,我怎样才能打印它们的行?
答案 0 :(得分:0)
Manager和DirectReports行有问题,Get-ADUser
cmdlet未正确执行,您使用它三次,每个属性一个,
此外,get-aduser (Get-ADUser...).manager or directreports
可能无法有效用于身份参数,因为它使用经理作为身份,如果您没有管理员或直接报告身份的广告,它将失败。
所以我建议您使用所需的属性获取ADUser一次,然后像这样使用它,
同样$ADUser = $null
将强制重置变量,这样你就不会为同一个用户重复行。
$users = @("user1", "user2", "user3")
$results = @()
foreach($user in $users) {
$ADUser = $null
$ADUser = Get-ADUser $user -Properties Manager,DirectReports
if ($ADUser) {
$Row = "" | Select Name,Manager,DirectReports
$Row.Name = $ADUser.Name
$Row.Manager = $ADUser.Manager
$Row.DirectReports = $ADUser.DirectReports
$results += $Row
}
}
$results