如果用户是“应用程序用户”和/或“应用程序测试用户”组的成员,则“值”列将显示相关组信息。如果用户不是任何组的成员,则会显示 NULL。我该怎么做?
$cyberarkAccounts = Get-ADUser -identity users01 -Properties samaccountname,enabled,memberof
$cyberarkAccountTable = @{}
foreach ($account in $cyberarkAccounts) {
$cyberarkAccountTable[$account.samaccountname] = $account.MemberOf | %{(Get-ADGroup $_).sAMAccountName} | Where-Object { $_ -like 'apps Users*' -or $_ -like 'apps test Users*' }
}
我的输出:
Name Value
--- ----
Users01
Users02 apps users
Users03 apps users,apps test Users
我想要的输出:
Name Value
--- ----
Users01 NULL
Users02 apps users
Users03 apps users,apps test Users
因此,如果您想在用户不是这些组的成员时显示
NULL
,唯一应该更改的应该是 if / else
(似乎您还缺少 -join ','
):
$cyberarkAccounts = Get-ADUser -Identity users01 -Properties samaccountname, enabled, memberOf
$cyberarkAccountTable = @{}
foreach ($account in $cyberarkAccounts) {
$result = $account.MemberOf |
ForEach-Object { (Get-ADGroup $_).sAMAccountName } |
Where-Object { $_ -like 'apps Users*' -or $_ -like 'apps test Users*' }
$cyberarkAccountTable[$account.samaccountname] = if ($result) { $result -join ',' } else { 'NULL' }
}
但是,如果您想对许多用户进行这些检查,这种方法确实非常低效,更好的方法是首先获取组成员身份并映射它们:
$targetGroups = 'apps Users', 'apps test Users'
$groupMap = @{} # maps key: each item in `$targetGroups` value: hashset with each group member samAccountName
$targetGroups | ForEach-Object {
$groupDn = (Get-ADGroup $_).DistinguishedName
$members = (Get-ADUser -LDAPFilter "(memberOf=$groupDn)").SamAccountName
$groupMap[$_] = [System.Collections.Generic.HashSet[string]]::new(
[string[]] $members)
}
$cyberarkAccounts = 'user1', 'user2', 'useretc' # these should be samAccountNames!
foreach ($account in $cyberarkAccounts) {
$membership = foreach ($group in $targetGroups) {
if ($groupMap[$group].Contains($account)) {
$group
}
}
[pscustomobject]@{
User = $account
Membership = if ($membership) { $membership -join ',' } else { 'NULL' }
}
}