Functions/Groups/New-GraphGroup.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
Function New-GraphGroup
{
    [CmdletBinding()]
    Param(      
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$DisplayName,

        [Parameter()]
        [string]$Description,

        [Parameter()]
        [bool]$MailEnabled = $true,

        [Parameter()]
        [string]$MailNickname,

        [Parameter()]
        [bool]$SecurityEnabled = $false, 

        [Parameter()]
        [string[]]$GroupTypes = @("Unified"),

        [Parameter()]
        [string[]]$OwnerIds = @(),

        [Parameter()]
        [string[]]$MemberIds = @()
    )

    if ([string]::IsNullOrEmpty($MailNickname))
        { $MailNickname = $DisplayName } # this might not be a good idea because of spaces etc. - let's start here for now (yagni)

    if ([string]::IsNullOrEmpty($Description))
        { $Description = $DisplayName }

    if ($SecurityEnabled -and $GroupTypes.Length -gt 0)
        { throw "You cannot set GroupTypes if you are creating a Security Group" }

    #TODO: more validation on GroupTypes values

    $body = (@{
        displayName     = $DisplayName
        description     = $Description
        mailEnabled     = $MailEnabled
        mailNickname    = $MailNickname
        securityEnabled = $SecurityEnabled
        groupTypes      = $GroupTypes
    }) | ConvertTo-Json

    $uri = $global:PowerGraph_BaseUrl + "groups"

    Write-Verbose "Adding new group: $DisplayName with $body"

    $group = Invoke-MSGraphRequest -Uri $uri -Method Post -Body $body

    if ($group -ne $null)
    {
        Write-Verbose "New group created with Id $($group.id)"

        #$OwnerIds | New-GraphGroupOwner -GroupId $group.id

        $MemberIds | New-GraphGroupMember -GroupId $group.id

        # see https://stackoverflow.com/questions/46467617/create-a-group-in-microsoft-graph-api-with-a-owner
    }
    
    return $group
}