AD组成员身份导出到单独的列



我想制作一个(希望(简单的CSV或XLSX,可以通过PowerShell ISE比较两个用户的AD组成员身份。目前,它有点广泛,尽管主要是";面包&黄油";脚本的:

Get-ADUser -Identity $User1 -Properties 'name' | Select-Object -Property Name | Export-CSV $CSVFile
try{Get-ADPrincipalGroupMembership $User1 | select name | Export-CSV $CSVFile -Append}
catch{Write-Host "Unable to locate $User1. Please check the ID and retry. $User1 will not be included in export if completed."}
{DBEngine.Idle} #For assistance in processing a break in the names visually on screen.
Get-ADUser -Identity $User2 -Properties 'name' | Select-Object -Property Name | Export-CSV $CSVFile -Append
try{Get-ADPrincipalGroupMembership $User2 | select name | Export-CSV $CSVFile -Append}
catch{Write-Host "Unable to locate $User2. Please check the ID and retry. $User2 will not be included in export if completed."}
Write-Host "
AD Groups assigned to $User1 and $User2 will also be exported to $CSVFile, unless halted. Check folder contents.
"

我有Read Host消息来定义$User1&User2以及$CSVFile的预定义名称约定。我收到的只是一个单列列表,其中包含用户的名称,然后是他们的组成员身份(按任何顺序(,所以我手动为第一个用户对组进行排序,然后为第二个用户进行排序。之后,我手动将$User2名称和组移到另一列。所以我的输出在CSV文件中是这样的:

|User1.Name|
|AD_Group_2|
|AD_Group_3|
|AD_Group_1|
|User2.Name|
|AD_Group_3|
|AD_Group_1|
|AD_Group_2|

因此,当每个用户的组数量明显不同时,这有点像一场狩猎。我想要的是这样的东西:

|User1.Name|User2.Name|
|AD_Group_1|AD_Group_1|
|AD_Group_2|AD_Group_2|
|AD_Group_3|AD_Group_3|

如果列不是按字母顺序排列的,我也不太担心,因为只要名称在顶部,我就可以很容易地对其进行排序。获取不同专栏中的信息是我的主要目标。

编辑:构建单独的工作表也可以。只是一个可以很容易地引用和排序的地方

非常感谢!

您的请求极不寻常。你可以用PowerShell或任何其他语言做任何事情,但你应该始终遵循标准,这真的不是标准。

代码的第一部分是做事的标准方式。例如,您可以使用它在PowerShell上进行比较,而不是在Excel上进行可视化比较。运行代码后,请检查$output1的输出。

话虽如此,以下是你想要的。。。

$User1 = "user1" # use SamAccountName or Read-Host
$User2 = "user2" # use SamAccountName or Read-Host
# add more as needed
#create array of all users
$users = @($User1, $User2)
# get information of all users from AD
$allUsers = $users | Get-ADUser
# gathers all users and groups from AD
$output1 = @()
foreach ( $user in $allUsers )
{
# new object
$out = New-Object -TypeName PSObject
# user
$out | Add-Member -MemberType NoteProperty -Name User -Value $user.Name
# all groups
$out | Add-Member -MemberType NoteProperty -Name Groups -Value (($user | Get-ADPrincipalGroupMembership).Name)
# add user details to object
$output1 += $out
}
#$output #check here
# number of users in list
$maxusers = $output1.Count
# find user with more groups
$max = 0
$output1 | ForEach-Object { if ($_.Groups.Count -gt $max){ $max = $_.Groups.Count } }
# creates alternative output
$output2 = @()
for ( $x = 0; $x -lt $max; $x++ )
{
# new object
$out = New-Object -TypeName PSObject
# iterate all groups
for  ( $y = 0; $y -lt $maxusers; $y++ )
{
# if the group is populated for the user, add it as a property
if ( $output1[$y].Groups[$x] )
{
$out | Add-Member -MemberType NoteProperty -Name $output1[$y].User -Value $output1[$y].Groups[$x]
}
}
# add user details to object
$output2 += $out
}
$output2 | FT # what you are looking for

$output2 | Export-Csv "C:folderout.csv"

最新更新