Проверьте, пуста ли группа AD - PullRequest
0 голосов
/ 25 июня 2019

Я ищу способ сначала проверить, пуста ли группа AD, и если это так, записать в файл CSV что-то вроде «$ GroupName + пусто».Я предполагаю, что это будет в конструкции IF-THEN, но обратите внимание на то, где разместить ее в моем коде ниже или в синтаксисе.Спасибо за вашу помощь.

#Script will export group members from the imported list of groups
#Import the AD Module necessary for the script to run
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

$resultsarray =@()

foreach ($group in $groups){

    $resultsarray += Get-ADGroupMember -Id $group -Server Server01.domain.com | Get-ADUser -Properties $UserProperties | select (@{n='FirstName';e={$_.GivenName}},
    @{n='LastName';e={$_.Surname}},'Name',@{e={$group};Label="GroupName"})

}
$resultsarray | Export-csv -path C:\temp\Groups_$(get-date -Format yyyy-MM-dd).csv -NTI

Ответы [ 2 ]

0 голосов
/ 26 июня 2019

После некоторых комментариев, я думаю, теперь я понимаю вопрос о том, когда он должен быть пустым или нет.
Поскольку 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') возвращаются по умолчанию

0 голосов
/ 25 июня 2019

Я не пробовал это, но это может быть что-то вроде

#Script will export group members from the imported list of groups
#Import the AD Module necessary for the script to run
Import-Module ActiveDirectory
#specify the file that contains group names
$groups = Get-Content C:\temp\grouplist.txt
$UserProperties = 'GivenName', 'Surname', 'Name'

$resultsarray =@()

foreach ($group in $groups){

    $result = Get-ADGroupMember -Id $group -Server Server01.domain.com | Get-ADUser -Properties $UserProperties | select (@{n='FirstName';e={$_.GivenName}},
    @{n='LastName';e={$_.Surname}},'Name',@{e={$group};Label="GroupName"})
    $resultsarray += if ($result) {$result} else {"$($group) is empty"}

}
$resultsarray | Export-csv -path C:\temp\Groups_$(get-date -Format yyyy-MM-dd).csv -NTI
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...