src/Classes.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
function Get-SkolniLoginClassId {
    param (
        [Parameter(Mandatory = $true)]
        $Name,
        [Parameter(Mandatory = $true)]
        $CurrentYear
    )
    [string]$id = "";
    [string]$separator = "";
    [int]$grade = 0;

    if ($Name -like "*. *") { $separator = ". "; }
    elseif ($Name -like "*.*") { $separator = "."; }
    else { $separator = ""; }

    $Name = $Name.Normalize("FormD") -replace '\p{M}', ''

    $splitted = $Name.Split($separator, [System.StringSplitOptions]::RemoveEmptyEntries);

    $parseResult = [int]::TryParse($splitted[0], [ref]$grade)
    if ($parseResult -eq $true) {
        $year = [int]$CurrentYear - ($grade - 1);

        $id = "$($year)-$($splitted[1])";
    }
    else {
        [System.Collections.ArrayList]$characters = $splitted[0].ToCharArray();

        foreach ($char in $characters) {
            if ([char]::IsDigit($char) -eq $true) {
                $grade = [int]::Parse($char);
                if ($characters.IndexOf($char) -gt 0) {
                    $characters[$characters.IndexOf($char)] = "X";
                }
                else {
                    $characters.RemoveAt(0);
                }
                break;
            }
        }
        $year = [int]$CurrentYear - ($grade - 1);

        $id = "$($year)-$($characters -join '')";
    }
    
    return $id;
}
function New-SkolniLoginClass {
    param (
        [Parameter(Mandatory = $true)]
        $Name,
        [Parameter(Mandatory = $true)]
        $CurrentYear,
        [Parameter(Mandatory = $true)]
        $Domain,
        [Parameter(Mandatory = $true)]
        $Path
    )

    $group = "";
    $id = Get-SkolniLoginClassId -Name $name -CurrentYear $CurrentYear;

    try {
        $group = Get-ADGroup $id -Property mail

        Write-Debug "Group $id exists, updating only DisplayName";
        $group | Set-ADGroup -DisplayName $Name

        if ($null -eq $group.mail) {
            $existingGroupWithSameMail = Get-ADGroup -Filter "mail -eq '$($group.name)@$Domain'"
            if($null -eq $existingGroupWithSameMail) {
                $group | Set-ADGroup -Replace @{mail = "$($group.name)@$Domain"}
            }
        }
    }
    catch {
        Write-Debug "Group doesn't exist yet, will create a new one with id: $id";
        
        $group = New-ADGroup -SamAccountName $id `
            -Name $id `
            -DisplayName $Name `
            -GroupScope Global `
            -GroupCategory Security `
            -OtherAttributes @{'mail' = "$id@$domain"} `
            -Path $Path `
            -PassThru
    }

    return $group;
}