src/ClassToDisplayName.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
function Set-SkolniLoginClassToDisplayName {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory = $true)]
        $User,
        [Parameter(Mandatory = $true)]
        [string]$ClassOU,
        [string[]]$IgnoreGroups
    )
    process {
        Write-Debug "Setting display name for $($User.sAMAccountName)"

        $adUser = Get-ADUser $User.SamAccountName -Properties "DisplayName","MemberOf"

        $candidates = New-Object System.Collections.ArrayList

        $adUser.MemberOf | ForEach-Object {
            $adGroup = Get-ADGroup $_ -Properties DisplayName
            if ($adGroup.DistinguishedName -like "*$ClassOU" -and $IgnoreGroups.IndexOf($_.SamAccountName) -eq -1) {
                $candidates.Add($adGroup);
            }
        }

        $lowest = $null;

        foreach($group in $candidates) {
            if($null -eq $lowest) {
                $lowest = $group;
                continue;
            }
            $year = $group.SamAccountName.Split("-")[0]
            $previousYear = $lowest.SamAccountName.Split("-")[0]

            if($year -lt $previousYear) {
                $lowest = $group;
            }
        }

        if($lowest) {
            $displayName = $adUser.DisplayName
            $withoutClass = $displayName.Split(" (")[0]
            Write-Debug "DisplayName set for $($User.sAMAccountName) to $withoutClass ($($lowest.DisplayName))"
            $adUser | Set-ADUser -DisplayName "$withoutClass ($($lowest.DisplayName))"
        }
    }
}