src/OrganizationalUnitByClass.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
47
48
49
50
51
52
53
54
55
function Set-SkolniLoginOrganizationalUnitByClass {
    [CmdletBinding()]
    param (
        [Parameter(ValueFromPipeline, Mandatory = $true)]
        $User,
        [Parameter(Mandatory = $true)]
        [string]$ClassOU,
        [Parameter(Mandatory = $true)]
        [string]$TargetOU,
        [string[]]$IgnoreGroups = @()
    )
    process {
        Write-Debug "Moving $($User.sAMAccountName) to respective class OU"
        
        $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) | Out-Null;
            }
        }

        $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 -and $null -ne $lowest.DisplayName) {
            Write-Debug "Found class $($lowest.sAMAccountName) for user $($User.sAMAccountName)"

            $ou = $null
            $ou = Get-ADOrganizationalUnit -Identity "OU=$($lowest.SamAccountName),$TargetOU" -ErrorAction SilentlyContinue
            if ($null -eq $ou) {
                Write-Debug "Organizational unit OU=$($lowest.SamAccountName),$TargetOU not found, creating..."
                $ou = New-ADOrganizationalUnit -Name $lowest.SamAccountName -Path $TargetOU
            }

            Write-Debug "Moving user $($User.DistinguishedName) to $($ou.DistinguishedName) OU"
            Move-ADObject -Identity $User.DistinguishedName -TargetPath $ou.DistinguishedName
        }
    }
}