После некоторых комментариев, я думаю, теперь я понимаю вопрос о том, когда он должен быть пустым или нет.
Поскольку Get-ADGroupMember
может возвращать объекты типа «пользователь», «группа» или «компьютер», код должен обрабатывать это и выводить различные результаты в зависимости от objectClass
каждого члена.
Однако, поскольку вы хотите получить результат в виде CSV-файла, вам нужно позаботиться о том, чтобы все объекты возвращали один и тот же структурированный объект.
Следующее должно делать то, что вы просите:
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'
# loop through the groups and collect group member info in a variable '$result'
$result = foreach ($group in $groups){
# get all members of the group and force it to be an array
$groupMembers = @(Get-ADGroupMember -Identity $group -Server 'Server01.domain.com')
if ($groupMembers.Count) {
foreach ($member in $groupMembers) {
switch ($member.objectClass) {
'user' {
# emit an object with the following user properties
$member | Get-ADUser -Properties $UserProperties |
Select-Object @{Name = 'FirstName'; Expression = {$_.GivenName}},
@{Name = 'LastName'; Expression = {$_.Surname}},
'Name',
@{Name = 'MemberType'; Expression = {$member.objectClass}},
@{Name = 'GroupName'; Expression = {$group}},
@{Name = 'GroupIsEmpty'; Expression = {$false}}
}
default {
# for other objects like groups or computers, keep the same structure
# and only fill in the Name, MemberType and GroupName properties
'' | Select-Object 'FirstName','LastName',
@{Name = 'Name'; Expression = {$member.Name}},
@{Name = 'MemberType'; Expression = {$member.objectClass}},
@{Name = 'GroupName'; Expression = {$group}},
@{Name = 'GroupIsEmpty'; Expression = {$false}}
}
}
}
}
else {
# the group is empty. Again: keep the same structure as above
'' | Select-Object 'FirstName','LastName','Name','MemberType',
@{Name = 'GroupName'; Expression = {$group}},
@{Name = 'GroupIsEmpty'; Expression = {$true}}
}
}
$outFile = 'C:\temp\Groups_{0:yyyy-MM-dd}.csv' -f (Get-Date)
$result | Export-csv -path $outFile -NoTypeInformation -Force
Примечание: в этом случае вам даже не нужно использовать параметр -Properties
в командлете Get-ADUser
, поскольку все требуемые свойства ($UserProperties = 'GivenName', 'Surname', 'Name'
) возвращаются по умолчанию