gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 01:29:09 27 4
gpt4 key购买 nike

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

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

GroupCode是 Activity 目录组的代码。

例:

首字母缩略词“ABC”映射到名为“Group_One”的广告组

GroupCode'DEF'映射到名为'Group_Two'的AD组

GroupCode“GHI”映射到名为“Group_Three”的广告组

这些广告组中的每个都有用户。
例:

广告“Group_One”中的用户:John Doe,Jessica Simmons

广告“Group_Two”中的用户:Carter McCarthy,Jeremy L

广告“Group_Three”中的用户:Alyson Carter,Eric Cross,Alejandra Fischer

本质上,我想创建某种映射或一种将CSV中的“GroupCode”链接到AD-Group的方法,然后在哈希表中列出其用户。

所需的输出为:
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

关于powershell - 从CSV创建映射以获取AD用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59869041/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com