functions/private/New-O365Group.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
function New-O365Group
{
param (

[Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true)]
        [ValidateNotNullOrEmpty()]
        [string]$GroupName,
        [Parameter(Mandatory=$false)]
        [ValidateSet('office','security')]
        [string] $Type = 'security',
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string] $Owner
        
)
process{
    Try
    {
        if($Type -eq 'security'){
        
            $groupexists = Get-MsolGroup -SearchString $GroupName
            if ($groupexists)
                {
                write-log -Message "Security Group $groupname already exists" -Type Information
                }
            Else
                {
                $newgroup = New-MsolGroup -DisplayName $groupname -Description $groupname
                write-log -Message "Security Group $GroupName created"
                $newgroup
                }
        } elseif($Type -eq 'office'){
            if($Group = get-unifiedgroup -identity $GroupName -ErrorAction Ignore){
                write-log -Message "Office Group $groupname already exists" -Type Information
                $Group
            } else {
                $OK = $false
                while((get-user -identity $Owner -ErrorAction SilentlyContinue) -eq $null){
                    write-log "Owner for group '$GroupName' is not yet provisioned. Retrying in 60 seconds..."
                    Start-Sleep -Seconds 60
                }
                $Group = new-unifiedGroup -displayname $GroupName -name $GroupName -owner $Owner -AccessType Private
                $Group          
                write-log -Message "Office Group $GroupName created with owner '$Owner'"
            }

        }

    }


    Catch 
    {
            throw "Can not create group $($GroupName): $_"


    }

}


    
        
}