functions/private/Add-O365UserToGroup.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
function Add-O365UserToGroup
{
    param(
    [Parameter(Mandatory=$true,
    ValueFromPipelineByPropertyName=$true)]
    [ValidateNotNullOrEmpty()]

    [string]$Username,

    [Parameter(Mandatory=$true,
    ValueFromPipelineByPropertyName=$true)]
    
    [string]$groupname,
    [ValidateSet('office','security')]
    [string] $Type = 'security'



    )
    Try
    {
        if($Type -eq 'security'){
            $group = Get-MsolGroup -searchstring $groupname
            $members = Get-MsolGroupMember -GroupObjectId $group.objectid
            $exists = 0
            foreach ($member in $members)
            {
                if ($member.displayname -eq $username){
                    write-log -message "User $username is already member of the group $groupname" -Type Information
                    $exists = 1
                }

            }

            if ($exists -eq 0)
            {
                $user = Get-MsolUser -SearchString $username
                $null = Add-MsolGroupMember -GroupObjectId $group.objectid -GroupMemberObjectId $user.objectid -GroupMemberType User
                write-log -Message "Added user $username to group $($groupname)"
            }
        } elseif($type -eq 'office'){
            $username = $Username.split('@')[0]
            $members = get-unifiedgrouplinks -identity $groupname -linktype members
            $found = $false
            foreach($member in $members){
                if($member.name -eq $Username){
                    $found = $true
                    break
                }
            }
            if($found -eq $true){
                write-log "User '$UserName' is already member of the Office Group '$GroupName'"
            } else {
                $OK = $false
                while($OK -eq $false){
                    try{
                        write-log -type verbose -message "Attempting to add '$UserName' to group '$groupname'"
                        while((get-user -ErrorAction Ignore -Identity $UserName) -eq $null){

                        }
                        $null = Add-UnifiedGroupLinks -LinkType members -Identity $groupname -Links $Username
                        
                        $OK = $true
                    } catch {
                        if($_.Exception.Message -like "*Couldn't find object*"){} else {throw $_}
                    }

                }
                write-log "User '$UserName' is now member of the Office Group '$GroupName'"
                
            }
            
        }




    }

    Catch
    {
        throw "Cannot add User $username to group $($groupname): $_"

    }




}