DSCResources/MSFT_SPUserProfileSyncService/MSFT_SPUserProfileSyncService.psm1

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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $UserProfileServiceAppName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [System.String] $Ensure = "Present",

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $FarmAccount,

        [Parameter()]
        [System.Boolean]
        $RunOnlyWhenWriteable,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Getting user profile sync service for $UserProfileServiceAppName"

    if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15)
    {
        throw [Exception] ("Only SharePoint 2013 is supported to deploy the user profile sync " + `
                           "service via DSC, as 2016 does not use the FIM based sync service.")
    }

    $farmAccount = Invoke-SPDSCCommand -Credential $InstallAccount `
                                       -Arguments $PSBoundParameters `
                                       -ScriptBlock {
        return Get-SPDscFarmAccount
    }

    if ($null -ne $farmAccount)
    {
        if ($PSBoundParameters.ContainsKey("InstallAccount") -eq $true)
        {
            # InstallAccount used
            if ($InstallAccount.UserName -eq $farmAccount.UserName)
            {
                throw ("Specified InstallAccount ($($InstallAccount.UserName)) is the Farm " + `
                       "Account. Make sure the specified InstallAccount isn't the Farm Account " + `
                       "and try again")
            }
        }
        else {
            # PSDSCRunAsCredential or System
            if (-not $Env:USERNAME.Contains("$"))
            {
                # PSDSCRunAsCredential used
                $localaccount = "$($Env:USERDOMAIN)\$($Env:USERNAME)"
                if ($localaccount -eq $farmAccount.UserName)
                {
                    throw ("Specified PSDSCRunAsCredential ($localaccount) is the Farm " + `
                           "Account. Make sure the specified PSDSCRunAsCredential isn't the " + `
                           "Farm Account and try again")
                }
            }
        }
    }
    else
    {
        throw ("Unable to retrieve the Farm Account. Check if the farm exists.")
    }

    $result = Invoke-SPDSCCommand -Credential $InstallAccount `
                                  -Arguments $PSBoundParameters `
                                  -ScriptBlock {
        $params = $args[0]

        $services = Get-SPServiceInstance -Server $env:COMPUTERNAME `
                        -ErrorAction SilentlyContinue

        if ($null -eq $services)
        {
            return @{
                UserProfileServiceAppName = $params.UserProfileServiceAppName
                Ensure = "Absent"
                RunOnlyWhenWriteable = $params.RunOnlyWhenWriteable
                InstallAccount = $params.InstallAccount
            }
        }

        $syncService = $services | Where-Object -FilterScript {
            $_.GetType().Name -eq "ProfileSynchronizationServiceInstance"
        }

        if ($null -eq $syncService)
        {
            $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain
            $currentServer = "$($env:COMPUTERNAME).$domain"
            $services = Get-SPServiceInstance -Server $currentServer `
                                                  -ErrorAction SilentlyContinue
            $syncService = $services | Where-Object -FilterScript {
                $_.GetType().Name -eq "ProfileSynchronizationServiceInstance"
            }
        }

        if ($null -eq $syncService)
        {
            return @{
                UserProfileServiceAppName = $params.UserProfileServiceAppName
                Ensure = "Absent"
                RunOnlyWhenWriteable = $params.RunOnlyWhenWriteable
                InstallAccount = $params.InstallAccount
            }
        }
        if ($null -ne $syncService.UserProfileApplicationGuid -and `
            $syncService.UserProfileApplicationGuid -ne [Guid]::Empty)
        {
            $upa = Get-SPServiceApplication -Identity $syncService.UserProfileApplicationGuid `
                                         -ErrorAction SilentlyContinue
        }
        if ($syncService.Status -eq "Online")
        {
            $localEnsure = "Present"
        }
        else
        {
            $localEnsure = "Absent"
        }

        return @{
            UserProfileServiceAppName = $upa.Name
            Ensure = $localEnsure
            FarmAccount = $params.FarmAccount
            RunOnlyWhenWriteable = $params.RunOnlyWhenWriteable
            InstallAccount = $params.InstallAccount
        }
    }
    return $result
}


function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $UserProfileServiceAppName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [System.String] $Ensure = "Present",

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $FarmAccount,

        [Parameter()]
        [System.Boolean]
        $RunOnlyWhenWriteable,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Setting user profile sync service for $UserProfileServiceAppName"

    $PSBoundParameters.Ensure = $Ensure

    if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15)
    {
        throw [Exception] ("Only SharePoint 2013 is supported to deploy the user profile sync " + `
                           "service via DSC, as 2016 does not use the FIM based sync service.")
    }

    $farmAccount = Invoke-SPDSCCommand -Credential $InstallAccount `
                                           -Arguments $PSBoundParameters `
                                           -ScriptBlock {
        return Get-SPDscFarmAccount
    }

    if ($null -ne $farmAccount)
    {
        if ($PSBoundParameters.ContainsKey("InstallAccount") -eq $true)
        {
            # InstallAccount used
            if ($InstallAccount.UserName -eq $farmAccount.UserName)
            {
                throw ("Specified InstallAccount ($($InstallAccount.UserName)) is the Farm " + `
                       "Account. Make sure the specified InstallAccount isn't the Farm Account " + `
                       "and try again")
            }
        }
        else {
            # PSDSCRunAsCredential or System
            if (-not $Env:USERNAME.Contains("$"))
            {
                # PSDSCRunAsCredential used
                $localaccount = "$($Env:USERDOMAIN)\$($Env:USERNAME)"
                if ($localaccount -eq $farmAccount.UserName)
                {
                    throw ("Specified PSDSCRunAsCredential ($localaccount) is the Farm " + `
                           "Account. Make sure the specified PSDSCRunAsCredential isn't the " + `
                           "Farm Account and try again")
                }
            }
        }
    }
    else
    {
        throw ("Unable to retrieve the Farm Account. Check if the farm exists.")
    }

    if ($PSBoundParameters.ContainsKey("RunOnlyWhenWriteable") -eq $true)
    {
        $databaseReadOnly = Test-SPDscUserProfileDBReadOnly `
                                -UserProfileServiceAppName $UserProfileServiceAppName `
                                -InstallAccount $InstallAccount

        if ($databaseReadOnly)
        {
            Write-Verbose -Message ("User profile database is read only, setting user profile " + `
                                   "sync service to not run on the local server")
            $PSBoundParameters.Ensure = "Absent"
        }
        else
        {
            $PSBoundParameters.Ensure = "Present"
        }
    }

    # Add the Farm Account to the local Admins group, if it's not already there
    $isLocalAdmin = Test-SPDSCUserIsLocalAdmin -UserName $farmAccount.UserName

    if (!$isLocalAdmin)
    {
        Write-Verbose -Message "Adding farm account to Local Administrators group"
        Add-SPDSCUserToLocalAdmin -UserName $farmAccount.UserName

        # Cycle the Timer Service and flush Kerberos tickets
        # so that it picks up the local Admin token
        Restart-Service -Name "SPTimerV4"

        Clear-SPDscKerberosToken -Account $farmAccount.UserName
    }

    $isInDesiredState = $false
    try
    {
        Invoke-SPDSCCommand -Credential $FarmAccount `
                            -Arguments ($PSBoundParameters,$farmAccount) `
                            -ScriptBlock {
            $params = $args[0]
            $farmAccount = $args[1]

            $currentServer = $env:COMPUTERNAME

            $services = Get-SPServiceInstance -Server $currentServer `
                                              -ErrorAction SilentlyContinue
            $syncService = $services | Where-Object -FilterScript {
                $_.GetType().Name -eq "ProfileSynchronizationServiceInstance"
            }
            if ($null -eq $syncService)
            {
                $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain
                $currentServer = "$currentServer.$domain"
                $syncService = $services | Where-Object -FilterScript {
                    $_.GetType().Name -eq "ProfileSynchronizationServiceInstance"
                }
            }
            if ($null -eq $syncService)
            {
                throw "Unable to locate a user profile sync service instance on $currentServer to start"
            }

            # Start the Sync service if it should be running on this server
            if (($params.Ensure -eq "Present") -and ($syncService.Status -ne "Online"))
            {
                $ups = Get-SPServiceApplication -Name $params.UserProfileServiceAppName `
                                                        -ErrorAction SilentlyContinue
                if ($null -eq $ups)
                {
                    throw [Exception] ("No User Profile Service Application was found " + `
                                       "named $($params.UserProfileServiceAppName)")
                }

                $userName = $farmAccount.UserName
                $password = $farmAccount.GetNetworkCredential().Password
                $ups.SetSynchronizationMachine($currentServer, $syncService.ID, $userName, $password)

                Start-SPServiceInstance -Identity $syncService.ID

                $desiredState = "Online"
            }
            # Stop the Sync service in all other cases
            else
            {
                Stop-SPServiceInstance -Identity $syncService.ID -Confirm:$false
                $desiredState = "Disabled"
            }

            $count = 0
            $maxCount = 20

            while (($count -lt $maxCount) -and ($syncService.Status -ne $desiredState))
            {
                if ($syncService.Status -ne $desiredState)
                {
                    Start-Sleep -Seconds 60
                }

                # Get the current status of the Sync service
                Write-Verbose -Message ("$([DateTime]::Now.ToShortTimeString()) - Waiting for user " + `
                                        "profile sync service to become '$desiredState' (waited " + `
                                        "$count of $maxCount minutes)")

                $services = Get-SPServiceInstance -Server $currentServer `
                                                  -ErrorAction SilentlyContinue
                $syncService = $services | Where-Object -FilterScript {
                    $_.GetType().Name -eq "ProfileSynchronizationServiceInstance"
                }
                $count++
            }
        }
    }
    finally
    {
        # Remove the Farm Account from the local Admins group, if it was added above
        if (!$isLocalAdmin)
        {
            Write-Verbose -Message "Removing farm account from Local Administrators group"
            Remove-SPDSCUserToLocalAdmin -UserName $farmAccount.UserName

            # Cycle the Timer Service and flush Kerberos tickets
            # so that it picks up the local Admin token
            Restart-Service -Name "SPTimerV4"

            Clear-SPDscKerberosToken -Account $farmAccount.UserName
        }
    }
    if($syncService.Status -ne $desiredState)
    {
        throw "An error occured. We couldn't properly set the User Profile Sync Service on the server."
    }
}

function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $UserProfileServiceAppName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [System.String] $Ensure = "Present",

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $FarmAccount,

        [Parameter()]
        [System.Boolean]
        $RunOnlyWhenWriteable,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    Write-Verbose -Message "Testing user profile sync service for $UserProfileServiceAppName"

    $PSBoundParameters.Ensure = $Ensure

    if ((Get-SPDSCInstalledProductVersion).FileMajorPart -ne 15)
    {
        throw [Exception] ("Only SharePoint 2013 is supported to deploy the user profile sync " + `
                           "service via DSC, as 2016 does not use the FIM based sync service.")
    }

    $CurrentValues = Get-TargetResource @PSBoundParameters

    if ($PSBoundParameters.ContainsKey("RunOnlyWhenWriteable") -eq $true)
    {
        $databaseReadOnly = Test-SPDscUserProfileDBReadOnly `
                                -UserProfileServiceAppName $UserProfileServiceAppName `
                                -InstallAccount $InstallAccount

        if ($databaseReadOnly)
        {
            Write-Verbose -Message ("User profile database is read only, setting user profile " + `
                                   "sync service to not run on the local server")
            $PSBoundParameters.Ensure = "Absent"
        }
        else
        {
            $PSBoundParameters.Ensure = "Present"
        }
    }

    Write-Verbose -Message "Testing for User Profile Synchronization Service"

    return Test-SPDscParameterState -CurrentValues $CurrentValues `
                                    -DesiredValues $PSBoundParameters `
                                    -ValuesToCheck @("Ensure")
}

function Test-SPDscUserProfileDBReadOnly()
{
    param(
        [Parameter(Mandatory = $true)]
        [String]
        $UserProfileServiceAppName,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        $InstallAccount
    )

    $databaseReadOnly = Invoke-SPDSCCommand -Credential $InstallAccount `
                                            -Arguments $UserProfileServiceAppName `
                                            -ScriptBlock {
        $UserProfileServiceAppName = $args[0]

        $serviceApps = Get-SPServiceApplication -Name $UserProfileServiceAppName `
                                                -ErrorAction SilentlyContinue
        if ($null -eq $serviceApps)
        {
            throw [Exception] ("No user profile service was found " + `
                               "named $UserProfileServiceAppName")
        }
        $ups = $serviceApps | Where-Object -FilterScript {
            $_.GetType().FullName -eq "Microsoft.Office.Server.Administration.UserProfileApplication"
        }

        $propType = $ups.GetType()
        $propData = $propType.GetProperties([System.Reflection.BindingFlags]::Instance -bor `
                                            [System.Reflection.BindingFlags]::NonPublic)
        $profileProp = $propData | Where-Object -FilterScript {
            $_.Name -eq "ProfileDatabase"
        }
        $profileDBName = $profileProp.GetValue($ups).Name

        $database = Get-SPDatabase | Where-Object -FilterScript {
            $_.Name -eq $profileDBName
        }
        return $database.IsReadyOnly
    }
    return $databaseReadOnly
}

Export-ModuleMember -Function *-TargetResource