DSCResources/MSFT_SPFarm/MSFT_SPFarm.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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
$script:resourceModulePath = Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent
$script:modulesFolderPath = Join-Path -Path $script:resourceModulePath -ChildPath 'Modules'

$script:resourceFarmHelperModulePath = Join-Path -Path $script:modulesFolderPath -ChildPath 'SharePointDsc.Farm'
Import-Module -Name (Join-Path -Path $script:resourceFarmHelperModulePath -ChildPath 'SPFarm.psm1')

function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Yes')]
        [String]
        $IsSingleInstance,

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

        [Parameter(Mandatory = $true)]
        [System.String]
        $FarmConfigDatabaseName,

        [Parameter(Mandatory = $true)]
        [System.String]
        $DatabaseServer,

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

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

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

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $Passphrase,

        [Parameter(Mandatory = $true)]
        [System.String]
        $AdminContentDatabaseName,

        [Parameter(Mandatory = $true)]
        [System.Boolean]
        $RunCentralAdmin,

        [Parameter()]
        [System.String]
        $CentralAdministrationUrl,

        [Parameter()]
        [ValidateRange(1, 65535)]
        [System.UInt32]
        $CentralAdministrationPort,

        [Parameter()]
        [System.String]
        [ValidateSet("NTLM", "Kerberos")]
        $CentralAdministrationAuth,

        [Parameter()]
        [System.String]
        [ValidateSet("Application",
            "ApplicationWithSearch",
            "Custom",
            "DistributedCache",
            "Search",
            "SingleServerFarm",
            "WebFrontEnd",
            "WebFrontEndWithDistributedCache")]
        $ServerRole,

        [Parameter()]
        [ValidateSet("Off", "On", "OnDemand")]
        [System.String]
        $DeveloperDashboard,

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

        [Parameter()]
        [System.Boolean]
        $SkipRegisterAsDistributedCacheHost = $true,

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

    Write-Verbose -Message "Getting the settings of the current local SharePoint Farm (if any)"

    if ($Ensure -eq "Absent")
    {
        $message = "SharePointDsc does not support removing a server from a farm, please set " + `
            "the ensure property to 'present'"
        Add-SPDscEvent -Message $message `
            -EntryType 'Error' `
            -EventID 100 `
            -Source $MyInvocation.MyCommand.Source
        throw $message
    }

    $supportsSettingApplicationCredentialKey = $false
    $installedVersion = Get-SPDscInstalledProductVersion
    switch ($installedVersion.FileMajorPart)
    {
        15
        {
            Write-Verbose -Message "Detected installation of SharePoint 2013"
        }
        16
        {
            if ($DeveloperDashboard -eq "OnDemand")
            {
                $message = "The DeveloperDashboard value 'OnDemand' is not allowed in SharePoint " + `
                    "2016 and 2019"
                Add-SPDscEvent -Message $message `
                    -EntryType 'Error' `
                    -EventID 100 `
                    -Source $MyInvocation.MyCommand.Source
                throw $message
            }

            if ($DeveloperDashboard -eq "On")
            {
                $message = "Please make sure you also provision the Usage and Health " +
                "service application to make sure the Developer Dashboard " +
                "works properly"
                Write-Verbose -Message $message
            }

            if ($installedVersion.ProductBuildPart.ToString().Length -eq 4)
            {
                Write-Verbose -Message "Detected installation of SharePoint 2016"
            }
            else
            {
                Write-Verbose -Message "Detected installation of SharePoint 2019"
                $supportsSettingApplicationCredentialKey = $true
            }
        }
        default
        {
            $message = ("Detected an unsupported major version of SharePoint. SharePointDsc only " +
                "supports SharePoint 2013, 2016 or 2019.")
            Add-SPDscEvent -Message $message `
                -EntryType 'Error' `
                -EventID 100 `
                -Source $MyInvocation.MyCommand.Source
            throw $message
        }
    }

    if ($PSBoundParameters.ContainsKey("ApplicationCredentialKey") -and
        -not $supportsSettingApplicationCredentialKey)
    {
        $message = ("Specifying ApplicationCredentialKey is only supported " +
            "on SharePoint 2019")
        Add-SPDscEvent -Message $message `
            -EntryType 'Error' `
            -EventID 100 `
            -Source $MyInvocation.MyCommand.Source
        throw $message
    }

    if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) -and
        $installedVersion.FileMajorPart -ne 16)
    {
        $message = "Server role is only supported in SharePoint 2016 and 2019."
        Add-SPDscEvent -Message $message `
            -EntryType 'Error' `
            -EventID 100 `
            -Source $MyInvocation.MyCommand.Source
        throw $message
    }

    if (($PSBoundParameters.ContainsKey("ServerRole") -eq $true) -and
        $installedVersion.FileMajorPart -eq 16 -and
        $installedVersion.FileBuildPart -lt 4456 -and
        ($ServerRole -eq "ApplicationWithSearch" -or
            $ServerRole -eq "WebFrontEndWithDistributedCache"))
    {
        $message = ("ServerRole values of 'ApplicationWithSearch' or " +
            "'WebFrontEndWithDistributedCache' require the SharePoint 2016 " +
            "Feature Pack 1 to be installed. See " +
            "https://support.microsoft.com/en-us/kb/3127940")
        Add-SPDscEvent -Message $message `
            -EntryType 'Error' `
            -EventID 100 `
            -Source $MyInvocation.MyCommand.Source
        throw $message
    }


    # Determine if a connection to a farm already exists
    $majorVersion = $installedVersion.FileMajorPart
    $regPath = "hklm:SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\$majorVersion.0\Secure\ConfigDB"
    $dsnValue = Get-SPDscRegistryKey -Key $regPath -Value "dsn" -ErrorAction SilentlyContinue

    if ($null -ne $dsnValue)
    {
        Write-Verbose -Message "This node has already been connected to a farm"
        $result = Invoke-SPDscCommand -Credential $InstallAccount `
            -Arguments $PSBoundParameters `
            -ScriptBlock {
            $params = $args[0]

            try
            {
                $spFarm = Get-SPFarm
            }
            catch
            {
                Write-Verbose -Message "Unable to detect local farm."
                return $null
            }

            if ($null -eq $spFarm)
            {
                return $null
            }

            $configDb = Get-SPDatabase | Where-Object -FilterScript {
                $_.Name -eq $spFarm.Name -and $_.Type -eq "Configuration Database"
            }

            if ($params.FarmAccount.UserName -eq $spFarm.DefaultServiceAccount.Name)
            {
                $farmAccount = $params.FarmAccount
            }
            else
            {
                $farmAccount = $spFarm.DefaultServiceAccount.Name
            }

            $centralAdminSite = Get-SPWebApplication -IncludeCentralAdministration |
                Where-Object -FilterScript {
                    $_.IsAdministrationWebApplication -eq $true
                }

            $centralAdminProvisioned = $false
            $ca = Get-SPServiceInstance -Server $env:ComputerName
            if ($null -ne $ca)
            {
                $ca = $ca | Where-Object -FilterScript {
                    $_.GetType().Name -eq "SPWebServiceInstance" -and
                    $_.Name -eq "WSS_Administration" -and
                    $_.Status -eq "Online"
                }
            }

            if ($null -ne $ca)
            {
                $centralAdminProvisioned = $true
            }

            $centralAdminAuth = $null
            if ($null -ne $centralAdminSite -and
                $centralAdminSite.IisSettings[0].DisableKerberos -eq $false)
            {
                $centralAdminAuth = "Kerberos"
            }
            else
            {
                $centralAdminAuth = "NTLM"
            }

            $admService = Get-SPDscContentService
            $developerDashboardSettings = $admService.DeveloperDashboardSettings
            $developerDashboardStatus = $developerDashboardSettings.DisplayLevel

            $returnValue = @{
                IsSingleInstance          = "Yes"
                FarmConfigDatabaseName    = $spFarm.Name
                DatabaseServer            = $configDb.NormalizedDataSource
                FarmAccount               = $farmAccount # Need to return this as a credential to match the type expected
                Passphrase                = $null
                AdminContentDatabaseName  = $centralAdminSite.ContentDatabases[0].Name
                RunCentralAdmin           = $centralAdminProvisioned
                CentralAdministrationUrl  = $centralAdminSite.Url.TrimEnd('/')
                CentralAdministrationPort = (New-Object -TypeName System.Uri $centralAdminSite.Url).Port
                CentralAdministrationAuth = $centralAdminAuth
                DeveloperDashboard        = $developerDashboardStatus
                ApplicationCredentialKey  = $null
            }
            $installedVersion = Get-SPDscInstalledProductVersion
            if ($installedVersion.FileMajorPart -eq 16)
            {
                $server = Get-SPServer -Identity $env:COMPUTERNAME -ErrorAction SilentlyContinue
                if ($null -ne $server -and $null -ne $server.Role)
                {
                    $returnValue.Add("ServerRole", $server.Role)
                }
                else
                {
                    $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain
                    $currentServer = "$($env:COMPUTERNAME).$domain"

                    $server = Get-SPServer -Identity $currentServer -ErrorAction SilentlyContinue
                    if ($null -ne $server -and $null -ne $server.Role)
                    {
                        $returnValue.Add("ServerRole", $server.Role)
                    }
                }
            }
            return $returnValue
        }

        if ($null -eq $result)
        {
            # The node is currently connected to a farm but was unable to retrieve the values
            # of current farm settings, most likely due to connectivity issues with the SQL box
            Write-Verbose -Message ("This server appears to be connected to a farm already, " +
                "but the configuration database is currently unable to be " +
                "accessed. Values returned from the get method will be " +
                "incomplete, however the 'Ensure' property should be " +
                "considered correct")
            return @{
                IsSingleInstance          = "Yes"
                FarmConfigDatabaseName    = $null
                DatabaseServer            = $null
                FarmAccount               = $null
                Passphrase                = $null
                AdminContentDatabaseName  = $null
                RunCentralAdmin           = $null
                CentralAdministrationUrl  = $null
                CentralAdministrationPort = $null
                CentralAdministrationAuth = $null
                ApplicationCredentialKey  = $null
                Ensure                    = "Present"
            }
        }
        else
        {
            $result.Add("Ensure", "Present")
            return $result
        }
    }
    else
    {
        Write-Verbose -Message "This node has never been connected to a farm"
        # Return the null return object
        return @{
            IsSingleInstance          = "Yes"
            FarmConfigDatabaseName    = $null
            DatabaseServer            = $null
            FarmAccount               = $null
            Passphrase                = $null
            AdminContentDatabaseName  = $null
            RunCentralAdmin           = $null
            CentralAdministrationUrl  = $null
            CentralAdministrationPort = $null
            CentralAdministrationAuth = $null
            ApplicationCredentialKey  = $null
            Ensure                    = "Absent"
        }
    }
}

function Set-TargetResource
{
    # Supressing the global variable use to allow passing DSC the reboot message
    [CmdletBinding()]
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "")]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Yes')]
        [String]
        $IsSingleInstance,

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

        [Parameter(Mandatory = $true)]
        [System.String]
        $FarmConfigDatabaseName,

        [Parameter(Mandatory = $true)]
        [System.String]
        $DatabaseServer,

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

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

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

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $Passphrase,

        [Parameter(Mandatory = $true)]
        [System.String]
        $AdminContentDatabaseName,

        [Parameter(Mandatory = $true)]
        [System.Boolean]
        $RunCentralAdmin,

        [Parameter()]
        [System.String]
        $CentralAdministrationUrl,

        [Parameter()]
        [ValidateRange(1, 65535)]
        [System.UInt32]
        $CentralAdministrationPort,

        [Parameter()]
        [System.String]
        [ValidateSet("NTLM", "Kerberos")]
        $CentralAdministrationAuth,

        [Parameter()]
        [System.String]
        [ValidateSet("Application",
            "ApplicationWithSearch",
            "Custom",
            "DistributedCache",
            "Search",
            "SingleServerFarm",
            "WebFrontEnd",
            "WebFrontEndWithDistributedCache")]
        $ServerRole,

        [Parameter()]
        [ValidateSet("Off", "On", "OnDemand")]
        [System.String]
        $DeveloperDashboard,

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

        [Parameter()]
        [System.Boolean]
        $SkipRegisterAsDistributedCacheHost = $true,

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

    Write-Verbose -Message "Setting local SP Farm settings"

    if ($Ensure -eq "Absent")
    {
        $message = ("SharePointDsc does not support removing a server from a farm, please set the " +
            "ensure property to 'present'")
        Add-SPDscEvent -Message $message `
            -EntryType 'Error' `
            -EventID 100 `
            -Source $MyInvocation.MyCommand.Source
        throw $message
    }

    $PSBoundParameters.SkipRegisterAsDistributedCacheHost = $SkipRegisterAsDistributedCacheHost

    if ($PSBoundParameters.ContainsKey("CentralAdministrationUrl"))
    {
        if ([string]::IsNullOrEmpty($CentralAdministrationUrl))
        {
            $PSBoundParameters.Remove('CentralAdministrationUrl') | Out-Null
        }
        else
        {
            $uri = $CentralAdministrationUrl -as [System.Uri]
            if ($null -eq $uri.AbsoluteUri -or $uri.scheme -notin ('http', 'https'))
            {
                $message = "CentralAdministrationUrl is not a valid URI. It should include the " + `
                    "scheme (http/https) and address."
                Add-SPDscEvent -Message $message `
                    -EntryType 'Error' `
                    -EventID 100 `
                    -Source $MyInvocation.MyCommand.Source
                throw $message
            }

            if ($PSBoundParameters.ContainsKey("CentralAdministrationPort"))
            {
                if ($uri.Port -ne $CentralAdministrationPort)
                {
                    $message = ("CentralAdministrationPort does not match port number specified in " + `
                            "CentralAdministrationUrl. Either make the values match or don't specify " + `
                            "CentralAdministrationPort.")
                    Add-SPDscEvent -Message $message `
                        -EntryType 'Error' `
                        -EventID 100 `
                        -Source $MyInvocation.MyCommand.Source
                    throw $message
                }
            }
        }
    }

    $CurrentValues = Get-TargetResource @PSBoundParameters

    # Set default values to ensure they are passed to Invoke-SPDscCommand
    if (-not $PSBoundParameters.ContainsKey("CentralAdministrationPort"))
    {
        # If CentralAdministrationUrl is specified, let's infer the port from the Url
        if ($PSBoundParameters.ContainsKey("CentralAdministrationUrl"))
        {
            $CentralAdministrationPort =
            $PSBoundParameters.CentralAdministrationPort =
            (New-Object -TypeName System.Uri $CentralAdministrationUrl).Port
        }
        else
        {
            $CentralAdministrationPort =
            $PSBoundParameters.CentralAdministrationPort = 9999
        }
    }

    if (-not $PSBoundParameters.ContainsKey("CentralAdministrationAuth"))
    {
        $CentralAdministrationAuth =
        $PSBoundParameters.CentralAdministrationAuth = "NTLM"
    }

    if ($CurrentValues.Ensure -eq "Present")
    {
        Write-Verbose -Message "Server already part of farm, updating settings"

        if ($CurrentValues.RunCentralAdmin -ne $RunCentralAdmin)
        {
            Invoke-SPDscCommand -Credential $InstallAccount `
                -Arguments @($PSBoundParameters, $MyInvocation.MyCommand.Source) `
                -ScriptBlock {
                $params = $args[0]
                $eventSource = $args[1]

                # Provision central administration
                if ($params.RunCentralAdmin -eq $true)
                {
                    Write-Verbose -Message "RunCentralAdmin set to true, provisioning Central Admin"
                    $serviceInstance = Get-SPServiceInstance -Server $env:COMPUTERNAME
                    if ($null -eq $serviceInstance)
                    {
                        $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain
                        $fqdn = "$($env:COMPUTERNAME).$domain"
                        $serviceInstance = Get-SPServiceInstance -Server $fqdn
                    }

                    if ($null -ne $serviceInstance)
                    {
                        $serviceInstance = $serviceInstance | Where-Object -FilterScript {
                            $_.GetType().Name -eq "SPWebServiceInstance" -and
                            $_.Name -eq "WSS_Administration"
                        }
                    }

                    if ($null -eq $serviceInstance)
                    {
                        $message = "Unable to locate Central Admin service instance on this server"
                        Add-SPDscEvent -Message $message `
                            -EntryType 'Error' `
                            -EventID 100 `
                            -Source $eventSource
                        throw $message
                    }
                    Start-SPServiceInstance -Identity $serviceInstance
                }
                else
                {
                    Write-Verbose -Message "RunCentralAdmin set to false, unprovisioning Central Admin"
                    $serviceInstance = Get-SPServiceInstance -Server $env:COMPUTERNAME
                    if ($null -eq $serviceInstance)
                    {
                        $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain
                        $fqdn = "$($env:COMPUTERNAME).$domain"
                        $serviceInstance = Get-SPServiceInstance -Server $fqdn
                    }

                    if ($null -ne $serviceInstance)
                    {
                        $serviceInstance = $serviceInstance | Where-Object -FilterScript {
                            $_.GetType().Name -eq "SPWebServiceInstance" -and
                            $_.Name -eq "WSS_Administration"
                        }
                    }

                    if ($null -eq $serviceInstance)
                    {
                        $message = "Unable to locate Central Admin service instance on this server"
                        Add-SPDscEvent -Message $message `
                            -EntryType 'Error' `
                            -EventID 100 `
                            -Source $eventSource
                        throw $message
                    }
                    Stop-SPServiceInstance -Identity $serviceInstance
                }
            }
        }

        if ($RunCentralAdmin)
        {
            # track whether or not we end up reprovisioning CA
            $reprovisionCentralAdmin = $false

            if ($PSBoundParameters.ContainsKey("CentralAdministrationUrl"))
            {
                # For the following scenarios, we should remove the CA web application and recreate it
                # CentralAdministrationUrl is passed in
                # AND Current CentralAdministrationUrl is not equal to new CentralAdministrationUrl
                # OR Current SecureBindings (HTTPS) or ServerBindings (HTTP) does not exist or doesn't
                # match desired url and port

                Write-Verbose -Message "Updating Central Admin URL configuration"
                Invoke-SPDscCommand -Credential $InstallAccount `
                    -Arguments $PSBoundParameters `
                    -ScriptBlock {
                    $params = $args[0]

                    $centralAdminSite = Get-SPWebApplication -IncludeCentralAdministration | Where-Object -FilterScript {
                        $_.IsAdministrationWebApplication
                    }

                    $isCentralAdminUrlHttps = (([System.Uri]$params.CentralAdministrationUrl).Scheme -eq 'https')

                    $desiredUri = [System.Uri]($params.CentralAdministrationUrl.TrimEnd('/'))
                    $currentUri = [System.Uri]$centralAdminSite.Url
                    if ($desiredUri.AbsoluteUri -ne $currentUri.AbsoluteUri)
                    {
                        Write-Verbose -Message ("Re-provisioning CA because $($currentUri.AbsoluteUri) " + `
                                "does not equal $($desiredUri.AbsoluteUri)")
                        $reprovisionCentralAdmin = $true
                    }
                    else
                    {
                        # check securebindings (https) or serverbindings (http)
                        # there should be an entry in the SecureBindings object of the
                        # SPWebApplication's IisSettings for the default zone
                        $iisBindings = $null
                        if ($isCentralAdminUrlHttps)
                        {
                            Write-Verbose -Message "Getting current secure bindings..."
                            $iisBindings = $centralAdminSite.GetIisSettingsWithFallback("Default").SecureBindings
                        }
                        else
                        {
                            Write-Verbose -Message "Getting current server bindings..."
                            $iisBindings = $centralAdminSite.GetIisSettingsWithFallback("Default").ServerBindings
                        }

                        if ($null -ne $iisBindings[0] -and (-not [string]::IsNullOrEmpty($iisBindings[0].HostHeader)))
                        {
                            # check to see if iisBindings host header and port match what we want them to be
                            if ($desiredUri.Host -ne $iisBindings[0].HostHeader -or
                                $desiredUri.Port -ne $iisBindings[0].Port)
                            {
                                Write-Verbose -Message ("Re-provisioning CA because $($desiredUri.Host) does not " + `
                                        "equal $($iisBindings[0].HostHeader) or $($desiredUri.Port) does not " + `
                                        "equal $($iisBindings[0].Port)")
                                $reprovisionCentralAdmin = $true
                            }
                        }
                        else
                        {
                            # iisBindings did not exist or did not contain a valid hostheader
                            Write-Verbose -Message ("Re-provisioning CA because IIS Bindings does not " + `
                                    "exist or does not contain a valid host header")
                            $reprovisionCentralAdmin = $true
                        }
                    }

                    if ($reprovisionCentralAdmin)
                    {
                        # Write-Verbose -Message "Removing Central Admin web application in order to reprovision it"
                        Remove-SPWebApplication -Identity $centralAdminSite.Url -Zone Default -DeleteIisSite

                        $farm = Get-SPFarm
                        $ca_service = $farm.Services | Where-Object -FilterScript { $_.TypeName -eq "Central Administration" }

                        Write-Verbose -Message "Re-provisioning Central Admin web application"
                        $webAppParams = @{
                            Identity             = $centralAdminSite.Url
                            Name                 = $ca_service.ApplicationPools.Name
                            Zone                 = "Default"
                            HostHeader           = $desiredUri.Host
                            Port                 = $desiredUri.Port
                            AuthenticationMethod = $params.CentralAdministrationAuth
                            SecureSocketsLayer   = $isCentralAdminUrlHttps
                        }
                        New-SPWebApplicationExtension @webAppParams
                    }
                }
            }
            elseif ($CurrentValues.CentralAdministrationPort -ne $CentralAdministrationPort)
            {
                Write-Verbose -Message "Updating CentralAdmin port to $CentralAdministrationPort"
                Invoke-SPDscCommand -Credential $InstallAccount `
                    -Arguments $PSBoundParameters `
                    -ScriptBlock {
                    $params = $args[0]

                    Set-SPCentralAdministration -Port $params.CentralAdministrationPort
                }
            }

            # if Authentication Method doesn't match and we haven't reprovisioned CA above, update auth method
            if ($CurrentValues.CentralAdministrationAuth -ne $CentralAdministrationAuth -and
                (-not $reprovisionCentralAdmin))
            {
                Write-Verbose -Message ("Updating CentralAdmin authentication method from " + `
                        "$($CurrentValues.CentralAdministrationAuth) to $CentralAdministrationAuth")
                Invoke-SPDscCommand -Credential $InstallAccount `
                    -Arguments $PSBoundParameters `
                    -ScriptBlock {
                    $params = $args[0]

                    $centralAdminSite = Get-SPWebApplication -IncludeCentralAdministration | Where-Object -FilterScript {
                        $_.IsAdministrationWebApplication
                    }

                    $centralAdminSite | Set-SPWebApplication -Zone "Default" -AuthenticationMethod $params.CentralAdministrationAuth
                }
            }
        }

        if ($CurrentValues.DeveloperDashboard -ne $DeveloperDashboard)
        {
            Write-Verbose -Message "Updating DeveloperDashboard to $DeveloperDashboard"
            Invoke-SPDscCommand -Credential $InstallAccount `
                -Arguments $PSBoundParameters `
                -ScriptBlock {
                $params = $args[0]

                Write-Verbose -Message "Updating Developer Dashboard setting"
                $admService = Get-SPDscContentService
                $developerDashboardSettings = $admService.DeveloperDashboardSettings
                $developerDashboardSettings.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::$($params.DeveloperDashboard)
                $developerDashboardSettings.Update()
            }
        }

        return
    }
    else
    {
        Write-Verbose -Message "Server not part of farm, creating or joining farm"

        $actionResult = Invoke-SPDscCommand -Credential $InstallAccount `
            -Arguments @($PSBoundParameters, $MyInvocation.MyCommand.Source, $PSScriptRoot) `
            -ScriptBlock {
            $params = $args[0]
            $eventSource = $args[1]
            $scriptRoot = $args[2]

            $modulePath = "..\..\Modules\SharePointDsc.Farm\SPFarm.psm1"
            Import-Module -Name (Join-Path -Path $scriptRoot -ChildPath $modulePath -Resolve)

            if ($params.UseSQLAuthentication -eq $true)
            {
                Write-Verbose -Message ("Using SQL authentication to create service application as " + `
                        "`$useSQLAuthentication is set to $($params.useSQLAuthentication).")
                $databaseCredentialsParam = @{
                    DatabaseCredentials = $params.DatabaseCredentials
                }
            }
            else
            {
                $databaseCredentialsParam = ""
            }

            $sqlInstanceStatus = Get-SPDscSQLInstanceStatus -SQLServer $params.DatabaseServer @databaseCredentialsParam

            if ($sqlInstanceStatus.MaxDOPCorrect -ne $true)
            {
                $message = "The MaxDOP setting is incorrect. Please correct before continuing."
                Add-SPDscEvent -Message $message `
                    -EntryType 'Error' `
                    -EventID 100 `
                    -Source $eventSource
                throw $message
            }

            $dbStatus = Get-SPDscConfigDBStatus -SQLServer $params.DatabaseServer `
                -Database $params.FarmConfigDatabaseName `
                @databaseCredentialsParam

            while ($dbStatus.Locked -eq $true)
            {
                Write-Verbose -Message ("[$([DateTime]::Now.ToShortTimeString())] The configuration " +
                    "database is currently being provisioned by a remote " +
                    "server, this server will wait for this to complete")
                Start-Sleep -Seconds 30
                $dbStatus = Get-SPDscConfigDBStatus -SQLServer $params.DatabaseServer `
                    -Database $params.FarmConfigDatabaseName `
                    @databaseCredentialsParam
            }

            if ($dbStatus.ValidPermissions -eq $false)
            {
                if ($dbStatus.DatabaseEmpty -eq $true)
                {
                    # If DatabaseEmpty is True most probably precreated databases are being used
                    Write-Verbose -Message ("IMPORTANT: Permissions check failed, but an empty " + `
                            "configDB '$($params.FarmConfigDatabaseName)' was found. Assuming that " + `
                            "precreated databases are being used.")
                }
                else
                {
                    # If DatabaseEmpty is False, then either the specified ConfigDB doesn't exist or
                    # is already provisioned
                    $message = "The current user does not have sufficient permissions to SQL Server"
                    Add-SPDscEvent -Message $message `
                        -EntryType 'Error' `
                        -EventID 100 `
                        -Source $eventSource
                    throw $message
                }
            }

            $executeArgs = @{
                DatabaseServer                     = $params.DatabaseServer
                DatabaseName                       = $params.FarmConfigDatabaseName
                Passphrase                         = $params.Passphrase.Password
                SkipRegisterAsDistributedCacheHost = $params.SkipRegisterAsDistributedCacheHost
            }

            $supportsSettingApplicationCredentialKey = $false

            if ($params.useSQLAuthentication -eq $true)
            {
                Write-Verbose -Message ("Using SQL authentication to connect to / create farm as " + `
                        "`$useSQLAuthentication is set to $($params.useSQLAuthentication).")
                $executeArgs.Add("DatabaseCredentials", $params.DatabaseCredentials)
            }
            else
            {
                Write-Verbose -Message ("`$useSQLAuthentication is false or not specified; using " + `
                        "default Windows authentication.")
            }

            $installedVersion = Get-SPDscInstalledProductVersion
            switch ($installedVersion.FileMajorPart)
            {
                15
                {
                    Write-Verbose -Message "Detected Version: SharePoint 2013"
                }
                16
                {
                    if ($params.ContainsKey("ServerRole") -eq $true)
                    {
                        if ($installedVersion.ProductBuildPart.ToString().Length -eq 4)
                        {
                            Write-Verbose -Message ("Detected Version: SharePoint 2016 - " +
                                "configuring server as $($params.ServerRole)")
                        }
                        else
                        {
                            Write-Verbose -Message ("Detected Version: SharePoint 2019 - " +
                                "configuring server as $($params.ServerRole)")
                            $supportsSettingApplicationCredentialKey = $true
                        }
                        $executeArgs.Add("LocalServerRole", $params.ServerRole)
                    }
                    else
                    {
                        if ($installedVersion.ProductBuildPart.ToString().Length -eq 4)
                        {
                            Write-Verbose -Message ("Detected Version: SharePoint 2016 - no server " +
                                "role provided, configuring server without a " +
                                "specific role")
                        }
                        else
                        {
                            Write-Verbose -Message ("Detected Version: SharePoint 2019 - no server " +
                                "role provided, configuring server without a " +
                                "specific role")
                            $supportsSettingApplicationCredentialKey = $true
                        }
                        $executeArgs.Add("ServerRoleOptional", $true)
                    }
                }
                Default
                {
                    $message = ("An unknown version of SharePoint (Major version $_) " +
                        "was detected. Only versions 15 (SharePoint 2013) and" +
                        "16 (SharePoint 2016 or SharePoint 2019) are supported.")
                    Add-SPDscEvent -Message $message `
                        -EntryType 'Error' `
                        -EventID 100 `
                        -Source $eventSource
                    throw $message
                }
            }

            if ($params.ContainsKey("ApplicationCredentialKey") -and
                -not $supportsSettingApplicationCredentialKey)
            {
                $message = ("Specifying ApplicationCredentialKey is only supported " +
                    "on SharePoint 2019")
                Add-SPDscEvent -Message $message `
                    -EntryType 'Error' `
                    -EventID 100 `
                    -Source $eventSource
                throw $message
            }

            if ($dbStatus.DatabaseExists -eq $true)
            {
                if ($dbStatus.DatabaseEmpty -eq $true)
                {
                    Write-Verbose -Message ("The SharePoint config database " +
                        "'$($params.FarmConfigDatabaseName)' exists but is empty, so " +
                        "this server will create the farm.")
                    $createFarm = $true
                }
                else
                {
                    Write-Verbose -Message ("The SharePoint config database " +
                        "'$($params.FarmConfigDatabaseName)' already exists, so " +
                        "this server will join the farm.")
                    $createFarm = $false
                }
            }
            elseif ($dbStatus.DatabaseExists -eq $false -and $params.RunCentralAdmin -eq $false)
            {
                # Only allow the farm to be created by a server that will run central admin
                # to avoid a ghost CA site appearing on this server and causing issues
                Write-Verbose -Message ("The SharePoint config database " +
                    "'$($params.FarmConfigDatabaseName)' does not exist, but " +
                    "this server will not be running the central admin " +
                    "website, so it will wait to join the farm rather than " +
                    "create one.")
                $createFarm = $false
            }
            else
            {
                Write-Verbose -Message ("The SharePoint config database " +
                    "'$($params.FarmConfigDatabaseName)' does not exist, so " +
                    "this server will create the farm.")
                $createFarm = $true
            }

            $farmAction = ""
            if ($createFarm -eq $false)
            {
                $dbStatus = Get-SPDscConfigDBStatus -SQLServer $params.DatabaseServer `
                    -Database $params.FarmConfigDatabaseName `
                    @databaseCredentialsParam
                $loopCount = 0
                while ($dbStatus.DatabaseExists -eq $false -and $loopCount -lt 15)
                {
                    Write-Verbose -Message ("The configuration database is not yet provisioned " +
                        "by a remote server, this server will wait for up to " +
                        "15 minutes for this to complete")
                    Start-Sleep -Seconds 60
                    $loopCount++
                    $dbStatus = Get-SPDscConfigDBStatus -SQLServer $params.DatabaseServer `
                        -Database $params.FarmConfigDatabaseName `
                        @databaseCredentialsParam
                }

                Write-Verbose -Message "The database exists, so attempt to join the server to the farm"

                # Remove the server role optional attribute as it is only used when creating
                # a new farm
                if ($executeArgs.ContainsKey("ServerRoleOptional") -eq $true)
                {
                    $executeArgs.Remove("ServerRoleOptional")
                }

                Write-Verbose -Message ("The server will attempt to join the farm now once every " +
                    "60 seconds for the next 15 minutes.")
                $loopCount = 0
                $connectedToFarm = $false
                $lastException = $null
                while ($connectedToFarm -eq $false -and $loopCount -lt 15)
                {
                    try
                    {
                        Write-Verbose -Message "Connecting to existing Config database"
                        Write-Verbose -Message "executeArgs is:"
                        foreach ($arg in $executeArgs.Keys)
                        {
                            if ($executeArgs.$arg -is [System.Management.Automation.PSCredential])
                            {
                                Write-Verbose -Message "$arg : $($executeArgs.$arg.UserName)"
                            }
                            else
                            {
                                Write-Verbose -Message "$arg : $($executeArgs.$arg)"
                            }
                        }

                        Connect-SPConfigurationDatabase @executeArgs | Out-Null
                        $connectedToFarm = $true
                    }
                    catch
                    {
                        $lastException = $_.Exception
                        Write-Verbose -Message ("$([DateTime]::Now.ToShortTimeString()) - An error " +
                            "occured joining config database " +
                            "'$($params.FarmConfigDatabaseName)' on " +
                            "'$($params.DatabaseServer)'. This resource will " +
                            "wait and retry automatically for up to 15 minutes. " +
                            "(waited $loopCount of 15 minutes)")
                        $loopCount++
                        Start-Sleep -Seconds 60
                    }
                }

                if ($connectedToFarm -eq $false)
                {
                    Write-Verbose -Message ("Unable to join config database. Throwing exception.")
                    $message = $lastException
                    Add-SPDscEvent -Message $message `
                        -EntryType 'Error' `
                        -EventID 100 `
                        -Source $eventSource
                    throw $message
                }
                $farmAction = "JoinedFarm"
            }
            else
            {
                Write-Verbose -Message "The database does not exist, so create a new farm"

                Write-Verbose -Message "Creating Lock to prevent two servers creating the same farm"
                $lockConnection = Add-SPDscConfigDBLock -SQLServer $params.DatabaseServer `
                    -Database $params.FarmConfigDatabaseName `
                    @databaseCredentialsParam

                try
                {
                    $executeArgs += @{
                        FarmCredentials                   = $params.FarmAccount
                        AdministrationContentDatabaseName = $params.AdminContentDatabaseName
                    }

                    Write-Verbose -Message "Creating new Config database"
                    Write-Verbose -Message "executeArgs is:"
                    foreach ($arg in $executeArgs.Keys)
                    {
                        if ($executeArgs.$arg -is [System.Management.Automation.PSCredential])
                        {
                            Write-Verbose -Message "$arg : $($executeArgs.$arg.UserName)"
                        }
                        else
                        {
                            Write-Verbose -Message "$arg : $($executeArgs.$arg)"
                        }
                    }
                    New-SPConfigurationDatabase @executeArgs

                    $farmAction = "CreatedFarm"
                }
                finally
                {
                    Write-Verbose -Message "Removing Lock"
                    Remove-SPDscConfigDBLock -SQLServer $params.DatabaseServer `
                        -Database $params.FarmConfigDatabaseName `
                        -Connection $lockConnection `
                        @databaseCredentialsParam
                }
            }

            # Run common tasks for a new server
            Write-Verbose -Message "Starting Install-SPHelpCollection"
            Install-SPHelpCollection -All | Out-Null

            Write-Verbose -Message "Starting Initialize-SPResourceSecurity"
            Initialize-SPResourceSecurity | Out-Null

            Write-Verbose -Message "Starting Install-SPService"
            Install-SPService | Out-Null

            Write-Verbose -Message "Starting Install-SPFeature"
            Install-SPFeature -AllExistingFeatures -Force | Out-Null

            if ($params.ContainsKey("ApplicationCredentialKey"))
            {
                Write-Verbose -Message "Setting application credential key"
                Set-SPApplicationCredentialKey -Password $params.ApplicationCredentialKey.Password
            }

            # Provision central administration
            if ($params.RunCentralAdmin -eq $true)
            {
                Write-Verbose -Message "RunCentralAdmin is True, provisioning Central Admin"
                $centralAdminSite = Get-SPWebApplication -IncludeCentralAdministration | Where-Object -FilterScript {
                    $_.IsAdministrationWebApplication -eq $true
                }

                $centralAdminProvisioned = $false
                if ((New-Object -TypeName System.Uri $centralAdminSite.Url).Port -eq $params.CentralAdministrationPort)
                {
                    $centralAdminProvisioned = $true
                }

                if ($centralAdminProvisioned -eq $false)
                {
                    New-SPCentralAdministration -Port $params.CentralAdministrationPort `
                        -WindowsAuthProvider $params.CentralAdministrationAuth

                    if (-not [string]::IsNullOrEmpty($params.CentralAdministrationUrl))
                    {
                        $centralAdminSite = Get-SPWebApplication -IncludeCentralAdministration | Where-Object -FilterScript {
                            $_.IsAdministrationWebApplication -eq $true
                        }

                        # cases where we need to reprovision CA:
                        # 1. desired Url is https
                        # 2. desired Url/port does not match current Url/port
                        # 3. IIS bindings don't match (shouldn't need this because case #2 should catch it in this case)
                        $reprovisionCentralAdmin = $false
                        $isCentralAdminUrlHttps = (([System.Uri]$params.CentralAdministrationUrl).Scheme -eq 'https')

                        $desiredUri = [System.Uri]($params.CentralAdministrationUrl.TrimEnd('/'))
                        $currentUri = [System.Uri]$centralAdminSite.Url

                        if ($isCentralAdminUrlHttps)
                        {
                            Write-Verbose -Message "Re-provisioning newly created CA because we want it to be HTTPS"
                            $reprovisionCentralAdmin = $true
                        }
                        elseif ($desiredUri.AbsoluteUri -ne $currentUri.AbsoluteUri)
                        {
                            Write-Verbose -Message ("Re-provisioning CA because $($currentUri.AbsoluteUri) " + `
                                    "does not equal $($desiredUri.AbsoluteUri)")
                            $reprovisionCentralAdmin = $true
                        }

                        if ($reprovisionCentralAdmin)
                        {
                            Write-Verbose -Message "Removing Central Admin web application"

                            # Wondering if -DeleteIisSite is necessary. Does this add more risk of ending up in
                            # a state without CA or a way to recover it?
                            Remove-SPWebApplication -Identity $centralAdminSite.Url -Zone Default -DeleteIisSite

                            Write-Verbose -Message "Reprovisioning Central Admin with SSL"

                            $webAppParams = @{
                                Identity             = $centralAdminSite.Url
                                Name                 = "SharePoint Central Administration v4"
                                Zone                 = "Default"
                                HostHeader           = $desiredUri.Host
                                Port                 = $desiredUri.Port
                                AuthenticationMethod = $params.CentralAdministrationAuth
                                SecureSocketsLayer   = $isCentralAdminUrlHttps
                            }

                            New-SPWebApplicationExtension @webAppParams
                        }
                    }
                }
                else
                {
                    $serviceInstance = Get-SPServiceInstance -Server $env:COMPUTERNAME
                    if ($null -eq $serviceInstance)
                    {
                        $domain = (Get-CimInstance -ClassName Win32_ComputerSystem).Domain
                        $fqdn = "$($env:COMPUTERNAME).$domain"
                        $serviceInstance = Get-SPServiceInstance -Server $fqdn
                    }

                    if ($null -ne $serviceInstance)
                    {
                        $serviceInstance = $serviceInstance | Where-Object -FilterScript {
                            $_.GetType().Name -eq "SPWebServiceInstance" -and
                            $_.Name -eq "WSS_Administration"
                        }
                    }

                    if ($null -eq $serviceInstance)
                    {
                        $message = "Unable to locate Central Admin service instance on this server"
                        Add-SPDscEvent -Message $message `
                            -EntryType 'Error' `
                            -EventID 100 `
                            -Source $eventSource
                        throw $message
                    }
                    Start-SPServiceInstance -Identity $serviceInstance
                }
            }

            Write-Verbose -Message "Starting Install-SPApplicationContent"
            Install-SPApplicationContent | Out-Null

            if ($params.ContainsKey("DeveloperDashboard") -and $params.DeveloperDashboard -ne "Off")
            {
                Write-Verbose -Message "Updating Developer Dashboard setting"
                $admService = Get-SPDscContentService
                $developerDashboardSettings = $admService.DeveloperDashboardSettings
                $developerDashboardSettings.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::$($params.DeveloperDashboard)
                $developerDashboardSettings.Update()
            }

            return $farmAction
        }

        if ($actionResult -eq "JoinedFarm")
        {
            Write-Verbose -Message "Starting timer service"
            Start-Service -Name sptimerv4

            Write-Verbose -Message ("Pausing for 5 minutes to allow the timer service to " +
                "fully provision the server")
            Start-Sleep -Seconds 300
            Write-Verbose -Message ("Join farm complete. Restarting computer to allow " +
                "configuration to continue")

            $global:DSCMachineStatus = 1
        }
    }
}

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

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

        [Parameter(Mandatory = $true)]
        [System.String]
        $FarmConfigDatabaseName,

        [Parameter(Mandatory = $true)]
        [System.String]
        $DatabaseServer,

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

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

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

        [Parameter(Mandatory = $true)]
        [System.Management.Automation.PSCredential]
        $Passphrase,

        [Parameter(Mandatory = $true)]
        [System.String]
        $AdminContentDatabaseName,

        [Parameter(Mandatory = $true)]
        [System.Boolean]
        $RunCentralAdmin,

        [Parameter()]
        [System.String]
        $CentralAdministrationUrl,

        [Parameter()]
        [ValidateRange(1, 65535)]
        [System.UInt32]
        $CentralAdministrationPort,

        [Parameter()]
        [System.String]
        [ValidateSet("NTLM", "Kerberos")]
        $CentralAdministrationAuth,

        [Parameter()]
        [System.String]
        [ValidateSet("Application",
            "ApplicationWithSearch",
            "Custom",
            "DistributedCache",
            "Search",
            "SingleServerFarm",
            "WebFrontEnd",
            "WebFrontEndWithDistributedCache")]
        $ServerRole,

        [Parameter()]
        [ValidateSet("Off", "On", "OnDemand")]
        [System.String]
        $DeveloperDashboard,

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

        [Parameter()]
        [System.Boolean]
        $SkipRegisterAsDistributedCacheHost = $true,

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

    Write-Verbose -Message "Testing local SP Farm settings"

    $PSBoundParameters.Ensure = $Ensure

    if ($PSBoundParameters.ContainsKey("CentralAdministrationUrl"))
    {
        if ([string]::IsNullOrEmpty($CentralAdministrationUrl))
        {
            $PSBoundParameters.Remove('CentralAdministrationUrl') | Out-Null
        }
        else
        {
            $uri = $CentralAdministrationUrl -as [System.Uri]
            if ($null -eq $uri.AbsoluteUri)
            {
                $message = ("CentralAdministrationUrl is not a valid URI. It should " +
                    "include the scheme (http/https) and address.")
                Add-SPDscEvent -Message $message `
                    -EntryType 'Error' `
                    -EventID 100 `
                    -Source $MyInvocation.MyCommand.Source
                throw $message
            }

            if ($PSBoundParameters.ContainsKey("CentralAdministrationPort"))
            {
                if ($uri.Port -ne $CentralAdministrationPort)
                {
                    $message = ("CentralAdministrationPort does not match port number specified " + `
                            "in CentralAdministrationUrl. Either make the values match or don't " + `
                            "specify CentralAdministrationPort.")
                    Add-SPDscEvent -Message $message `
                        -EntryType 'Error' `
                        -EventID 100 `
                        -Source $MyInvocation.MyCommand.Source
                    throw $message
                }
            }
        }
    }

    $CurrentValues = Get-TargetResource @PSBoundParameters

    Write-Verbose -Message "Current Values: $(Convert-SPDscHashtableToString -Hashtable $CurrentValues)"
    Write-Verbose -Message "Target Values: $(Convert-SPDscHashtableToString -Hashtable $PSBoundParameters)"

    $result = Test-SPDscParameterState -CurrentValues $CurrentValues `
        -Source $($MyInvocation.MyCommand.Source) `
        -DesiredValues $PSBoundParameters `
        -ValuesToCheck @("Ensure",
        "RunCentralAdmin",
        "CentralAdministrationUrl",
        "CentralAdministrationPort",
        "CentralAdministrationAuth",
        "DeveloperDashboard")

    Write-Verbose -Message "Test-TargetResource returned $result"

    return $result
}

function Export-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.String])]
    param
    (
        [Parameter()]
        [System.String]
        $ServerName,

        [Parameter()]
        [System.Boolean]
        $RunCentralAdmin
    )

    $spMajorVersion = (Get-SPDscInstalledProductVersion).FileMajorPart
    $ParentModuleBase = Get-Module "SharePointDsc" -ListAvailable | Select-Object -ExpandProperty Modulebase
    $module = Join-Path -Path $ParentModuleBase -ChildPath "\DSCResources\MSFT_SPFarm\MSFT_SPFarm.psm1" -Resolve

    $Content = " SPFarm " + [System.Guid]::NewGuid().ToString() + "`r`n {`r`n"
    $params = Get-DSCFakeParameters -ModulePath $module
    $params.CentralAdministrationPort = 443

    <# If not SP2016 or above, remove the server role param. #>
    if ($spMajorVersion -lt 16)
    {
        $params.Remove("ServerRole")
    }

    <# if not 2019 or above, remove the ApplicationCredentialKey param#>
    if ($spMajorVersion -lt 19)
    {
        $params.Remove("ApplicationCredentialKey")
    }

    <# Can't have both the InstallAccount and PsDscRunAsCredential variables present. Remove InstallAccount if both are there. #>
    if ($params.Contains("InstallAccount"))
    {
        $params.Remove("InstallAccount")
    }

    $params.FarmAccount = $Global:spFarmAccount
    $params.Passphrase = $Global:spFarmAccount
    $results = Get-TargetResource @params

    <# Remove the default generated PassPhrase and ensure the resulting Configuration Script will prompt user for it. #>
    $results.Remove("Passphrase");

    $dbServer = $results.DatabaseServer
    $results.DatabaseServer = "`$ConfigurationData.NonNodeData.DatabaseServer"

    if ($null -ne $results.CentralAdministrationUrl -and $results.CentralAdministrationUrl.ToLower() -like 'http://*')
    {
        $results.Remove("CentralAdministrationUrl") | Out-Null
    }

    if ($DynamicCompilation)
    {
        Add-ConfigurationDataEntry -Node "NonNodeData" -Key "DatabaseServer" -Value 'localhost' -Description "Name of the Database Server associated with the destination SharePoint Farm;"
    }
    else
    {
        Add-ConfigurationDataEntry -Node "NonNodeData" -Key "DatabaseServer" -Value $dbServer -Description "Name of the Database Server associated with the destination SharePoint Farm;"
    }

    if ($null -eq (Get-ConfigurationDataEntry -Node "NonNodeData" -Key "PassPhrase"))
    {
        Add-ConfigurationDataEntry -Node "NonNodeData" -Key "PassPhrase" -Value "pass@word1" -Description "SharePoint Farm's PassPhrase;"
    }

    $Content += " Passphrase = New-Object System.Management.Automation.PSCredential ('Passphrase', (ConvertTo-SecureString -String `$ConfigurationData.NonNodeData.PassPhrase -AsPlainText -Force));`r`n"

    if (!$results.ContainsKey("RunCentralAdmin"))
    {
        $results.Add("RunCentralAdmin", $RunCentralAdmin)
    }

    if ($StandAlone)
    {
        $results.RunCentralAdmin = $true
    }

    if ($spMajorVersion -ge 16)
    {
        if (!$results.Contains("ServerRole"))
        {
            $results.Add("ServerRole", "`$Node.ServerRole")
        }
        else
        {
            $results["ServerRole"] = "`$Node.ServerRole"
        }
    }
    else
    {
        $results.Remove("ServerRole")
    }
    $results = Repair-Credentials -results $results
    $results.FarmAccount = Resolve-Credentials -UserName $results.FarmAccount
    $currentBlock = Get-DSCBlock -Params $results -ModulePath $module
    $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "DatabaseServer"
    $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "PsDscRunAsCredential"
    $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "FarmAccount"
    if ($spMajorVersion -ge 16)
    {
        $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "ServerRole"
    }
    $Content += $currentBlock
    $Content += " }`r`n"

    <# SPFarm Feature Section #>
    if (($Global:ExtractionModeValue -eq 3 -and $Quiet) -or $Global:ComponentsToExtract.Contains("SPFeature"))
    {
        $Properties = @{
            Scope = "Farm"
        }
        $Content += Read-TargetResource -ResourceName 'SPFeature' -ExportParams $Properties
    }
    return $Content
}

Export-ModuleMember -Function *-TargetResource