简体   繁体   中英

PowerShell Group-Object with dot notation

I'm trying to create one e-mail per manager, where the user accounts he is responsible for in active directory, will expire within a given time frame. It's already working quite well but I have some issue in grouping the Managers.

It would be nice if it was possible to group the managers together and then collect all the users where that specific manager is responsible for in a small HTML table ( $Rows ). The HTML-code is not the problem, but iterating the users for that manager is my issue.

The code:

$OU = 'OU=BBB,OU=EU,DC=domain,DC=net', 'OU=AAA,OU=EU,DC=domain,DC=net'
[INT]$Days = 30
$ExpUsers=$Objects=@()
Foreach ($O in $OU) {
    $ExpUsers += Search-ADAccount -AccountExpiring -TimeSpan "$Days.00:00:00" -UsersOnly -SearchBase $O | 
        Select -ExpandProperty SamAccountName
}
Foreach ($E in $ExpUsers) {
    $User = Get-ADUser $E -Properties * | Select SamAccountName, EmailAddress, GivenName, 
                                            SurName, AccountExpirationDate, Manager, DisplayName   
    $Manager = Get-ADUser $User.Manager -Properties * | Select SamAccountName, EmailAddress, GivenName, SurName
    $Objects += [PSCustomObject]@{
        User = $User
        Manager = $Manager
    }
}
$Objects | Group-Object Manager.SamAccountName | % {        
    $Rows=@()
    foreach($M in $_) {
        # Create HTML row for each user with the same manager
        $M.Group.Manager.SurName
    }
}

Grouping the managers can be done easily like this:

$Objects.Manager | Group-Object SamAccountName

However, when I do it like this I can't use the User properties anymore because they haven't been piped to Group-Object .

What is the best way to overcome this hurdle? I could of course create my object like this:

$Objects += [PSCustomObject]@{
    UserSamAccountName = $User.SamAccountName
    UserGivenName = $User.GivenName
    ManagerSamAccountName = $Manager.SamAccountName
    ManagerGivenName = $Manager.GivenName
}

But this solution doesn't seem to be so flexible if I want to add stuff later on.

我在这里的示例中找到了答案:

$Objects | Group-Object {$_.Manager.SamAccountName} | % { $_.Group.User.GivenName}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM