从 CSV 创建映射以获取 AD 用户



我是PowerShell的新手。我正在尝试从我的 CSV 创建一个映射,该映射会将 AD 组中的用户列出到哈希表中。 我的csv看起来像这样:

ClientCode,GroupCode
1234,ABC
1234,DEF
1235,ABC

组码是 Active-Directory 组的代码。

例:

组首字母缩略词"ABC"映射到名为"Group_One"的 AD 组

组码"DEF"映射到名为"Group_Two"的AD组

组码"GHI"映射到名为"Group_Three"的AD组

这些 AD 组中的每一个都有用户。 例:

AD 'Group_One'中的用户:John Doe,Jessica Simmons

AD 'Group_Two'中的用户:卡特·麦卡锡、杰里米·

AD 'Group_Three'中的用户:Alyson Carter、Eric Cross、Alejandra Fischer

从本质上讲,我想创建某种映射或一种方法来将 CSV 中的"组码"链接到 AD 组,然后在哈希表中列出其用户。

所需的输出为:

ClientCode GroupUsers      
---------- ---------      
1234       John Doe, Jessica Simmons, Carter McCarthy, Jeremy L        
1235       John Doe, Jessica Simmons
1236       Alyson Carter, Eric Cross, Alejandra Fischer

您可以使用代码到组名的映射创建一个查找哈希表,并使用它来检索所有用户名,如下所示:

# create a mapping hash for the group codes to the real group names
$groupsMap = @{
'ABC' = 'Group_One'
'DEF' = 'Group_Two'
'GHI' = 'Group_Three'
#etc.
}
$csv = Import-Csv -Path 'ClientGroupCodes.csv'
# loop though the csv items, group by property ClientCode
$result = $csv | Group-Object ClientCode | ForEach-Object {
# get an array of the various group codes inside each client group
$groupCodes = $_.Group.GroupCode | Select-Object -Unique
# loop through these codes, find the real names from the hash 
# and collect the user names in variable $groupUsers
$groupUsers = New Object 'System.Collections.Generic.List[string]'
foreach ($code in $groupCodes) {
# test if the group code can be found in the hash
if ($groupsMap.ContainsKey($code)) {
$users = [string[]](Get-ADGroupMember -Identity $groupsMap[$code] | Where-Object { $_.objectClass -eq 'user' }).Name
$groupUsers.AddRange($users)
}
else {
Write-Warning "No mapping found for group code $code"
}
}
# output an object with the properties combined
[PsCustomObject]@{
'ClientCode' = $_.Name
'GroupUsers' = ($groupUsers.ToArray() | Sort-Object -Unique) -join ', '
}
}
# output on screen
$result
# output to CSV file
$result | Export-Csv -Path 'GroupUsersPerClient.csv' -NoTypeInformation

为了帮助您入门,您可以将 GroupCode 添加到 AD Group 对象中的一个注释字段中。然后用

get-adgroup Group1 -Properties info

您将能够访问该数据。

我看到您或某人在这里发布了相同的问题,似乎有人建议: https://community.spiceworks.com/topic/2253543-creating-mapping-from-csv-to-get-ad-users?page=1#entry-8732830

最新更新