functions/public/New-FlexdeskOfficeDeployment.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
function New-FlexdeskOfficeDeployment {

    [cmdletbinding(DefaultParameterSetName="TenantId")]
    [OutputType([psobject])]
    param(
    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    # The location of the input CSV file.
    [String] $CSV,
    [parameter(ParameterSetName="TenantId",Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [string] $TenantId,
    [parameter(ParameterSetName="TenantDomain",Mandatory=$true)]
    #[ValidateNotNullOrEmpty()]
    [string] $TenantDomain,
    [parameter()]
    [string] $MailDomain,
    #[ValidateNotNullOrEmpty()]
    [parameter()]
    [ValidateNotNullOrEmpty()]
    [string] $DefaultPassword = $(New-SWRandomPassword),
    [parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [pscredential] $Credential = (Get-Credential -Message "Please provide your Partner Credentials"),
    [Parameter(DontShow)]
    [ValidateNotNullOrEmpty()]
    [object] $SyncHash = $null,
    [Parameter()]
    [switch] $NoUpdateCheck,
    [Parameter(DontShow=$true)]
    [string] $Log
    )
    
    begin{
        $ATPLicenseName = "ADALLOM_O365"
        $Continue = $true
        if([string]::IsNullOrEmpty($Log) -eq $false){
            if(test-path $Log){} else {
                $Log = Start-Log
            }
        } else {
            $Log = Start-Log
        }
        $PSDefaultParameterValues = @{"Write-Log:Log"="$Log"}
        if(!$PSBoundParameters.ContainsKey('NoUpdateCheck')){
        Test-ModuleVersion -ModuleName FlexdeskBluePrint
    }


        try{
            if((Test-AADPasswordComplexity -MinimumLength 8 -Password $DefaultPassword) -eq $false){
                    write-log -type error -message "Password does not meet complexity requirements"
                    return
            }
            $DeploymentJob = new-object psobject -Property @{
                Type="Office"
                Duration = "00:00:00"
                Completed = $false
                Status = @{
                    ProvisionedUsers = @()
                    ProvisionedGroups = @()
                }
                Error=$null
                Log = $Log
            }
            if($SyncHash){
                $SyncHash.DeploymentJob = ([ref]$DeploymentJob).value
            }
            $DeploymentStart = get-date
            $null = Connect-MsolService -Credential $Credential
            # Hash both internal and external tenant information
        <#    $TenantDomainHash = @{}
   foreach($Item in (get-msolpartnercontract -all)){
    $TenantHash.Add($Item.TenantId,$Item.DefaultDomainName)
   }
   $CompanyInfo = Get-MsolCompanyInformation
   $TenantHash.Add($CompanyInfo.ObjectId,$CompanyInfo.InitialDomain)
   #>

            $Tenant = Get-Tenant -TenantId $TenantId -TenantDomain $TenantDomain
            $TenantId = $Tenant.Id
            
            $PSDefaultParameterValues.Add('*-MSOL*:TenantId',$TenantId)
            $DefaultDomain = $(
                $VerifiedDomains = Get-MsolDomain -Status Verified
                if($MailDomain){
                    if($VerifiedDomains.Name -contains $MailDomain){
                        $MailDomain
                        write-log "Using the specified domain '$MailDomain' as mail domain"
                    } else {
                        throw "Mail Domain not present or verified in the tenant"
                    }
                } else {
                    $MailDomain = ($VerifiedDomains.where{$_.IsDefault -eq $true}).Name
                    $MailDomain
                    write-log "Using the default domain ($MailDomain) as mail domain"
                    
                }
        
            )
                
            #write-log "Using default domain '$DefaultDomain' as mail suffix"
            
            write-log "Getting available licenses from O365"
            $Licenses = Get-O365License -TenantId $TenantId
            write-log "Generating O365 Deployment Inventory"
            $Inventory = ConvertTo-O365 -Path $CSV -Licenses $Licenses -Separator ','
            write-log "Creating CSP admin account"
            $CSPAdminCredential = new-cspadmin -DomainName $MailDomain

            
            
        } catch {
            Write-Log -Type Error -Message "Error during Office 365 Connection: $_"
            $Continue = $false
            
        }
    }
    
    
    
    process{
        if($Continue -eq $false){
            return
        }
        try {
            
            ##### Exchange Connection
            write-log "Opening remote session to Exchange online"
            $Connect = $false
            while($Connect -eq $false){
                try{
                    $Session = Connect-O365 -Credential $CSPAdminCredential
                    $Connect = $true
                } catch {
                    if($_.Exception.Message -like "*403*"){
                        write-log "CSP Admin Account not ready yet. Retrying Connection in 60 seconds"
                        start-sleep -Seconds 60
                    } else {throw $_}
                }
            }
            write-log -type verbose -message "Connection succeeded. Importing Exchange Online PS Session."
            #####
            
            write-log -type information -message "Provisioning Users"
            $OneDriveUsers = @()
            $EnableATP = $false
            $i = 0
            foreach($User in $Inventory.Users){
                $i++
                Write-Progress -Id 1 -Activity "Deploying O365 Solution"`
                -Status "Provisioning Users "`
                -CurrentOperation "$i/$($Inventory.Users.Count)"`
                -PercentComplete (($i/$($Inventory.Users.Count))*100)
                $UserParameters = @{
                    Username=[Regex]::Replace("$($User.First).$($User.Last)@$($DefaultDomain)",'[^a-zA-Z0-9\@\.\-]', '')
                    FirstName=$User.First
                    LastName=$User.Last
                    Title=$User.Title
                    Password=$DefaultPassword
                    License=$($User.Licenses.Id)
                    MobilePhone=$User.Mobile
                    Country=$User.Country
                }
                $ReturnUser = New-O365User @UserParameters
                $User.Login = $ReturnUser.SignInName
                $User.Password = $DefaultPassword
                $Inventory.Groups|where{$_.Owner -eq $User}|foreach{$_.Owner = $User}
                
                $DeploymentJob.Status.ProvisionedUsers += $User
                $OneDriveUsers += $UserParameters.UserName
                if(($EnableATP -eq $false) -and ($User.Licenses|where{$_.Name -eq $ATPLicenseName})){
                    $EnableATP = $true
                }
                
            }
            Write-Progress -Id 1 -Completed -Activity "Deploying 0365 Solution"
            #write-log "Waiting some time to allow the user mailboxes to provision"
            #Start-Sleep -Seconds 30
            if($EnableATP){
                # Disabled due to testing issues
                <#write-log "At least one O365 ATP License is assigned, setting up ATP policies and rules"
    Write-Progress -Id 1 -Activity "Deploying O365 Solution"`
    -Status "Provisioning ATP "
    try {
     Enable-O365ATP -MailDomain $DefaultDomain
    } catch {
     write-log -type warning -message $_
    }
    Write-Progress -Id 1 -Completed -Activity "Deploying 0365 Solution" #>

            }

            write-log -type information -message "Provisioning Groups"
            $i = 1
            if($Inventory.Groups.Count -gt 0){
                foreach($Group in $Inventory.Groups){
                    Write-Progress -Id 1 -Activity "Deploying O365 Solution"`
                    -Status "Provisioning Groups"`
                    -CurrentOperation "$i/$($Inventory.Groups.Count)"`
                    -PercentComplete (($i/$($Inventory.Groups.Count))*100)
                    $null = New-O365Group -GroupName $Group.Name -Type office -owner ($Group.Owner.Login.split('@')[0])
                    $DeploymentJob.Status.ProvisionedGroups += $Group
                    $i++
                }
                Write-Progress -Id 1 -Completed -Activity "Deploying 0365 Solution"
                write-log "Populating Group Memberships"
                $i = 1
                foreach($User in $Inventory.Users){
                    Write-Progress -Id 1 -Activity "Deploying O365 Solution"`
                    -Status "Provisioning Group Memberships"`
                    -CurrentOperation "$i/$($Inventory.Users.Count)"`
                    -PercentComplete (($i/$($Inventory.Users.Count))*100)
                    foreach($Group in $User.Groups){
                        if(($Group.Owner).Login -ne $User.Login){
                            $null = Add-O365UserToGroup -UserName $User.Login -GroupName $Group.Name -Type Office
                        } else {
                            write-log -type information -message "$User is owner of the group $Group, membership creation skipped"
                        }
                    }
                    $i++
                }
                Write-Progress -Id 1 -Completed -Activity "Deploying 0365 Solution"
            }

            write-log -type information -message "Provisioning Onedrives"
            Write-Progress -Id 1 -Activity "Deploying O365 Solution"`
                -Status "Provisioning Onedrives"`
                -PercentComplete -1
            $OnMicrosoftDomain = ((Get-MsolDomain).where{$_.Name -like "*onmicrosoft.com"}).Name
            $TenantName = $OnMicrosoftDomain.split(".")[0]
            $TenantSPAdminUrl = "https://$($TenantName)-admin.sharepoint.com"
            write-log -message "Using $TenantSPAdminUrl as admin url for SP online" -type verbose
            $null = Initialize-O365OneDrive -Users $OneDriveUsers -Credential $CSPAdminCredential -SPOAdminUrl $TenantSPAdminUrl
            Write-Progress -Id 1 -Completed -Activity "Deploying 0365 Solution"
            
            
            
            

        } catch {
            $DeploymentJob.Error = $_
            write-log -type error -message "$_ @ $($_.InvocationInfo.ScriptLineNumber) - $($_.InvocationInfo.Line))"  
        }
        finally{
            get-pssession|Remove-PSSession
            $DeploymentEnd = get-date
            $DeploymentDuration = New-TimeSpan -Start $DeploymentStart -End $DeploymentEnd
            $DeploymentJob.Duration = $("{0:HH:mm:ss}" -f ([datetime]$DeploymentDuration.Ticks))
            $DeploymentJob.Completed = $true
            ([ref]$DeploymentJob).Value
        }
        
    }
    end{
        write-log -message "Deployment Complete"
    }
}