DSCResources/MSFT_SPSearchServiceApp/MSFT_SPSearchServiceApp.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
function Get-TargetResource
{
    # Ignoring this because we need to generate a stub credential to return up the current
    # crawl account as a PSCredential
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [System.String]
        $Name,

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

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

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

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

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

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

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

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

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

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

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

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

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

    Write-Verbose -Message "Getting Search service application '$Name'"

    $result = Invoke-SPDscCommand -Credential $InstallAccount `
        -Arguments @($PSBoundParameters, $PSScriptRoot) `
        -ScriptBlock {
        $params = $args[0]
        $scriptRoot = $args[1]

        $modulePath = "..\..\Modules\SharePointDsc.Search\SPSearchServiceApp.psm1"
        Import-Module -Name (Join-Path -Path $scriptRoot -ChildPath $modulePath -Resolve) -Verbose:$false

        [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
        [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint.Administration")
        [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search.Administration")
        [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server.Search")
        [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Server")

        $serviceAppPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool `
            -ErrorAction SilentlyContinue
        if ($null -eq $serviceAppPool)
        {
            Write-Verbose -Message ("Specified service application pool $($params.ApplicationPool) " + `
                    "does not exist.")
        }

        $serviceApps = Get-SPServiceApplication | Where-Object -FilterScript {
            $_.Name -eq $params.Name
        }

        $nullReturn = @{
            Name            = $params.Name
            ApplicationPool = $params.ApplicationPool
            Ensure          = "Absent"
        }

        if ($null -eq $serviceApps)
        {
            return $nullReturn
        }
        $serviceApp = $serviceApps | Where-Object -FilterScript {
            $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
        }

        if ($null -eq $serviceApp)
        {
            return $nullReturn
        }
        else
        {
            $c = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($serviceApp.Name)
            $sc = New-Object -TypeName Microsoft.Office.Server.Search.Administration.Content `
                -ArgumentList $c;
            $dummyPassword = ConvertTo-SecureString -String "-" -AsPlainText -Force
            if ($null -ne $sc.DefaultGatheringAccount)
            {
                $defaultAccount = New-Object -TypeName System.Management.Automation.PSCredential `
                    -ArgumentList @($sc.DefaultGatheringAccount, $dummyPassword)
            }

            $cloudIndex = $false
            $version = Get-SPDscInstalledProductVersion
            if (($version.FileMajorPart -gt 15) `
                    -or ($version.FileMajorPart -eq 15 -and $version.FileBuildPart -ge 4745))
            {
                $cloudIndex = $serviceApp.CloudIndex
            }

            $pName = $null;
            $serviceAppProxies = Get-SPServiceApplicationProxy -ErrorAction SilentlyContinue
            if ($null -ne $serviceAppProxies)
            {
                $serviceAppProxy = $serviceAppProxies | Where-Object -FilterScript {
                    $serviceApp.IsConnected($_)
                }
                if ($null -ne $serviceAppProxy)
                {
                    $pName = $serviceAppProxy.Name
                }
            }

            if ($params.useSQLAuthentication -eq $true)
            {
                $farmAccountPermissionsNeedCorrecting = $false
            }
            else
            {
                Write-Verbose -Message "Checking Farm account permissions"
                $farmAccountPermissionsNeedCorrecting = $false

                $farmAccount = (Get-SPFarm).DefaultServiceAccount.Name
                $dbServer = $serviceApp.SearchAdminDatabase.NormalizedDataSource

                Write-Verbose -Message "Checking Admin Database"
                $adminDB = $serviceApp.SearchAdminDatabase.Name

                Write-Verbose -Message "Checking Admin Database: $adminDB"
                $farmAccountPermissionsNeedCorrecting = (Confirm-UserIsDBOwner -SQLServer $dbServer `
                        -Database $adminDB `
                        -User $farmAccount `
                        -DatabaseCredentials $params.DatabaseCredentials) -eq $false
                Write-Verbose -Message "Farm Account Permissions Need Correcting: $farmAccountPermissionsNeedCorrecting"

                Write-Verbose -Message "Checking Analytics reporting Database"
                foreach ($database in $serviceApp.AnalyticsReportingDatabases)
                {
                    $analyticsDB = $database.Name

                    Write-Verbose -Message "Checking Analytics reporting Database: $analyticsDB"
                    if ($farmAccountPermissionsNeedCorrecting -eq $false)
                    {
                        $farmAccountPermissionsNeedCorrecting = (Confirm-UserIsDBOwner -SQLServer $dbServer `
                                -Database $analyticsDB `
                                -User $farmAccount `
                                -DatabaseCredentials $params.DatabaseCredentials) -eq $false
                    }
                    Write-Verbose -Message "Farm Account Permissions Need Correcting: $farmAccountPermissionsNeedCorrecting"
                }

                Write-Verbose -Message "Checking Crawl Database(s)"
                if ($farmAccountPermissionsNeedCorrecting -eq $false)
                {
                    foreach ($database in (Get-SPEnterpriseSearchCrawlDatabase -SearchApplication $serviceApp))
                    {
                        $crawlDB = $database.Database.Name
                        $dbServer = $database.Database.NormalizedDataSource

                        Write-Verbose -Message "Checking Crawl Database: $crawlDB"
                        $farmAccountPermissionsNeedCorrecting = (Confirm-UserIsDBOwner -SQLServer $dbServer `
                                -Database $crawlDB `
                                -User $farmAccount `
                                -DatabaseCredentials $params.DatabaseCredentials) -eq $false
                        Write-Verbose -Message "Farm Account Permissions Need Correcting: $farmAccountPermissionsNeedCorrecting"
                    }
                }

                Write-Verbose -Message "Checking Links Database(s)"
                if ($farmAccountPermissionsNeedCorrecting -eq $false)
                {
                    foreach ($database in (Get-SPEnterpriseSearchLinksDatabase -SearchApplication $serviceApp))
                    {
                        $linksDB = $database.Database.Name
                        $dbServer = $database.Database.NormalizedDataSource

                        Write-Verbose -Message "Checking Links Database: $linksDB"
                        $farmAccountPermissionsNeedCorrecting = (Confirm-UserIsDBOwner -SQLServer $dbServer `
                                -Database $linksDB `
                                -User $farmAccount `
                                -DatabaseCredentials $params.DatabaseCredentials) -eq $false
                        Write-Verbose -Message "Farm Account Permissions Need Correcting: $farmAccountPermissionsNeedCorrecting"
                    }
                }
            }

            $returnVal = @{
                Name                        = $serviceApp.DisplayName
                ProxyName                   = $pName
                ApplicationPool             = $serviceApp.ApplicationPool.Name
                DatabaseName                = $serviceApp.SearchAdminDatabase.Name
                DatabaseServer              = $serviceApp.SearchAdminDatabase.NormalizedDataSource
                Ensure                      = "Present"
                SearchCenterUrl             = $serviceApp.SearchCenterUrl
                DefaultContentAccessAccount = $defaultAccount
                CloudIndex                  = $cloudIndex
                AlertsEnabled               = $serviceApp.AlertsEnabled
                FixFarmAccountPermissions   = $farmAccountPermissionsNeedCorrecting
            }
            return $returnVal
        }
    }
    return $result
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Write-Verbose -Message "Setting Search service application '$Name'"

    if ($UseSQLAuthentication -eq $true)
    {
        Write-Verbose ("Cannot check Farm Account permissions when SQL " + `
                "DatabaseCredentials are specified.")
        Write-Verbose "Setting FixFarmAccountPermissions to False"
        $PSBoundParameters.FixFarmAccountPermissions = $false
    }
    else
    {
        $PSBoundParameters.FixFarmAccountPermissions = $FixFarmAccountPermissions
    }

    $result = Get-TargetResource @PSBoundParameters

    if ($result.Ensure -eq "Absent" -and $Ensure -eq "Present")
    {
        # Create the service app as it doesn't exist
        Write-Verbose -Message "Creating Search Service Application $Name"
        Invoke-SPDscCommand -Credential $InstallAccount `
            -Arguments @($PSBoundParameters, $MyInvocation.MyCommand.Source) `
            -ScriptBlock {
            $params = $args[0]
            $eventSource = $args[1]

            $serviceAppPool = Get-SPServiceApplicationPool $params.ApplicationPool
            if ($null -eq $serviceAppPool)
            {
                $message = ("Specified service application pool $($params.ApplicationPool) does not " + `
                        "exist. Please make sure it exists before continuing.")
                Add-SPDscEvent -Message $message `
                    -EntryType 'Error' `
                    -EventID 100 `
                    -Source $eventSource
                throw $message
            }

            $serviceInstance = Get-SPEnterpriseSearchServiceInstance -Local
            Start-SPEnterpriseSearchServiceInstance -Identity $serviceInstance `
                -ErrorAction SilentlyContinue
            $newParams = @{
                Name            = $params.Name
                ApplicationPool = $params.ApplicationPool
            }
            if ($params.ContainsKey("DatabaseServer") -eq $true)
            {
                $newParams.Add("DatabaseServer", $params.DatabaseServer)
            }
            if ($params.ContainsKey("DatabaseName") -eq $true)
            {
                $newParams.Add("DatabaseName", $params.DatabaseName)
            }

            if ($params.useSQLAuthentication -eq $true)
            {
                Write-Verbose -Message "Using SQL authentication to create service application as `$useSQLAuthentication is set to $($params.useSQLAuthentication)."
                $newParams.Add("DatabaseUsername", $params.DatabaseCredentials.Username)
                $newParams.Add("DatabasePassword", $params.DatabaseCredentials.Password)
            }
            else
            {
                Write-Verbose -Message "`$useSQLAuthentication is false or not specified; using default Windows authentication."
            }

            if ($params.ContainsKey("CloudIndex") -eq $true -and $params.CloudIndex -eq $true)
            {
                $version = Get-SPDscInstalledProductVersion
                if (($version.FileMajorPart -gt 15) `
                        -or ($version.FileMajorPart -eq 15 -and $version.FileBuildPart -ge 4745))
                {
                    $newParams.Add("CloudIndex", $params.CloudIndex)
                }
                else
                {
                    $message = ("Please install SharePoint 2019, 2016 or SharePoint 2013 with August " + `
                            "2015 CU or higher before attempting to create a cloud enabled " + `
                            "search service application")
                    Add-SPDscEvent -Message $message `
                        -EntryType 'Error' `
                        -EventID 100 `
                        -Source $eventSource
                    throw $message
                }
            }

            $app = New-SPEnterpriseSearchServiceApplication @newParams
            if ($app)
            {
                if ($null -eq $params.ProxyName)
                {
                    $pName = "$($params.Name) Proxy"
                }
                else
                {
                    $pName = $params.ProxyName
                }

                Write-Verbose -Message "Creating proxy with name $pName"
                New-SPEnterpriseSearchServiceApplicationProxy -Name $pName -SearchApplication $app

                if ($params.ContainsKey("DefaultContentAccessAccount") -eq $true)
                {
                    Write-Verbose -Message ("Setting DefaultContentAccessAccount to " + `
                            $params.DefaultContentAccessAccount.UserName)
                    $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool
                    $account = $params.DefaultContentAccessAccount
                    $setParams = @{
                        ApplicationPool                     = $appPool
                        Identity                            = $app
                        DefaultContentAccessAccountName     = $account.UserName
                        DefaultContentAccessAccountPassword = $account.Password
                    }
                    Set-SPEnterpriseSearchServiceApplication @setParams
                }

                if ($params.ContainsKey("SearchCenterUrl") -eq $true)
                {
                    Write-Verbose -Message "Setting SearchCenterUrl to $($params.SearchCenterUrl)"
                    $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                        $_.Name -eq $params.Name -and `
                            $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
                    }
                    $serviceApp.SearchCenterUrl = $params.SearchCenterUrl
                    $serviceApp.Update()
                }

                if ($params.ContainsKey("AlertsEnabled") -eq $true)
                {
                    Write-Verbose -Message "Setting AlertsEnabled to $($params.AlertsEnabled)"
                    $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                        $_.Name -eq $params.Name -and `
                            $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
                    }
                    $serviceApp.AlertsEnabled = $params.AlertsEnabled
                    $serviceApp.Update()
                }
            }
        }
    }

    if ($result.Ensure -eq "Present" -and $Ensure -eq "Present")
    {
        # Update the service app that already exists
        Write-Verbose -Message "Updating Search Service Application $Name"
        Invoke-SPDscCommand -Credential $InstallAccount `
            -Arguments @($PSBoundParameters, $result) `
            -ScriptBlock {
            $params = $args[0]
            $result = $args[1]

            $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                $_.Name -eq $params.Name -and `
                    $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
            }

            if ($null -eq $params.ProxyName)
            {
                $pName = "$($params.Name) Proxy"
            }
            else
            {
                $pName = $params.ProxyName
            }

            if ($result.ProxyName -ne $pName)
            {
                if ($null -eq $result.ProxyName)
                {
                    Write-Verbose -Message "Creating proxy with name $pName"
                    New-SPEnterpriseSearchServiceApplicationProxy -Name $pName -SearchApplication $serviceApp
                }
                else
                {
                    Write-Verbose -Message "Updating proxy name to $pName"
                    $serviceAppProxy = Get-SPServiceApplicationProxy | Where-Object -FilterScript {
                        $_.Name -eq $result.ProxyName
                    }
                    $serviceAppProxy.Name = $pName
                    $serviceAppProxy.Update()
                }
            }

            $setParams = @{
                Identity = $serviceApp
            }

            if ($result.ApplicationPool -ne $params.ApplicationPool)
            {
                Write-Verbose -Message "Updating ApplicationPool to $($params.ApplicationPool)"

                $appPool = Get-SPServiceApplicationPool -Identity $params.ApplicationPool
                $setParams.Add("ApplicationPool", $appPool)
            }

            if ($params.ContainsKey("DefaultContentAccessAccount") -eq $true -and `
                    $result.DefaultContentAccessAccount.UserName -ne $params.DefaultContentAccessAccount.UserName)
            {
                Write-Verbose -Message ("Updating DefaultContentAccessAccount to " + `
                        $params.DefaultContentAccessAccount.UserName)

                $account = $params.DefaultContentAccessAccount
                $setParams.Add("DefaultContentAccessAccountName", $account.UserName)
                $setParams.Add("DefaultContentAccessAccountPassword", $account.Password)
            }

            if ($setParams.Count -gt 1)
            {
                Set-SPEnterpriseSearchServiceApplication @setParams
            }

            if ($params.ContainsKey("SearchCenterUrl") -eq $true -and `
                    $result.SearchCenterUrl -ne $params.SearchCenterUrl)
            {
                Write-Verbose -Message "Updating SearchCenterUrl to $($params.SearchCenterUrl)"
                $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                    $_.Name -eq $params.Name -and `
                        $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
                }
                $serviceApp.SearchCenterUrl = $params.SearchCenterUrl
                $serviceApp.Update()
            }

            if ($params.ContainsKey("AlertsEnabled") -eq $true -and `
                    $result.AlertsEnabled -ne $params.AlertsEnabled)
            {
                Write-Verbose -Message "Updating AlertsEnabled to $($params.AlertsEnabled)"
                $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                    $_.Name -eq $params.Name -and `
                        $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
                }
                $serviceApp.AlertsEnabled = $params.AlertsEnabled
                $serviceApp.Update()
            }
        }
    }

    # Only check and correct when Ensure=Present, FixFarmAccountPermissions=True and the permissions are incorrect
    if ($Ensure -eq "Present" -and `
            $FixFarmAccountPermissions -eq $true -and `
            $result.FixFarmAccountPermissions -eq $true)
    {
        Write-Verbose -Message "Fixing database permissions for Search Service Application $Name"
        Invoke-SPDscCommand -Credential $InstallAccount `
            -Arguments @($PSBoundParameters, $PSScriptRoot) `
            -ScriptBlock {
            $params = $args[0]
            $scriptRoot = $args[1]

            $modulePath = "..\..\Modules\SharePointDsc.Search\SPSearchServiceApp.psm1"
            Import-Module -Name (Join-Path -Path $scriptRoot -ChildPath $modulePath -Resolve) -Verbose:$false

            $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                $_.Name -eq $params.Name -and `
                    $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
            }

            $farmAccount = (Get-SPFarm).DefaultServiceAccount.Name
            $dbServer = $serviceApp.SearchAdminDatabase.NormalizedDataSource

            Write-Verbose -Message "Checking and correcting Admin Database"
            $adminDB = $serviceApp.SearchAdminDatabase.Name
            if ((Confirm-UserIsDBOwner -SQLServer $dbServer `
                        -Database $adminDB `
                        -User $farmAccount `
                        -DatabaseCredentials $params.DatabaseCredentials) -eq $false)
            {
                Set-UserAsDBOwner -SQLServer $dbServer `
                    -Database $adminDB `
                    -User $farmAccount `
                    -DatabaseCredentials $params.DatabaseCredentials
            }

            Write-Verbose -Message "Checking and correcting Analytics reporting Database"
            foreach ($database in $serviceApp.AnalyticsReportingDatabases)
            {
                $analyticsDB = $database.Name
                if ((Confirm-UserIsDBOwner -SQLServer $dbServer `
                            -Database $analyticsDB `
                            -User $farmAccount `
                            -DatabaseCredentials $params.DatabaseCredentials) -eq $false)
                {
                    Set-UserAsDBOwner -SQLServer $dbServer `
                        -Database $analyticsDB `
                        -User $farmAccount `
                        -DatabaseCredentials $params.DatabaseCredentials
                }
            }

            Write-Verbose -Message "Checking and correcting Crawl Database(s)"
            foreach ($database in (Get-SPEnterpriseSearchCrawlDatabase -SearchApplication $serviceApp))
            {
                $crawlDB = $database.Database.Name
                Write-Verbose -Message " * Processing $crawlDB"

                $dbServer = $database.Database.NormalizedDataSource
                if ((Confirm-UserIsDBOwner -SQLServer $dbServer `
                            -Database $crawlDB `
                            -User $farmAccount `
                            -DatabaseCredentials $params.DatabaseCredentials) -eq $false)
                {
                    Set-UserAsDBOwner -SQLServer $dbServer `
                        -Database $crawlDB `
                        -User $farmAccount `
                        -DatabaseCredentials $params.DatabaseCredentials
                }
            }

            Write-Verbose -Message "Checking and correcting Links Database(s)"
            foreach ($database in (Get-SPEnterpriseSearchLinksDatabase -SearchApplication $serviceApp))
            {
                $linksDB = $database.Database.Name
                Write-Verbose -Message " * Processing $linksDB"

                $dbServer = $database.Database.NormalizedDataSource
                if ((Confirm-UserIsDBOwner -SQLServer $dbServer `
                            -Database $linksDB `
                            -User $farmAccount `
                            -DatabaseCredentials $params.DatabaseCredentials) -eq $false)
                {
                    Set-UserAsDBOwner -SQLServer $dbServer `
                        -Database $linksDB `
                        -User $farmAccount `
                        -DatabaseCredentials $params.DatabaseCredentials
                }
            }
        }
    }

    if ($Ensure -eq "Absent")
    {
        # The service app should not exit
        Write-Verbose -Message "Removing Search Service Application $Name"
        Invoke-SPDscCommand -Credential $InstallAccount `
            -Arguments $PSBoundParameters `
            -ScriptBlock {
            $params = $args[0]

            $serviceApp = Get-SPServiceApplication | Where-Object -FilterScript {
                $_.Name -eq $params.Name -and `
                    $_.GetType().FullName -eq "Microsoft.Office.Server.Search.Administration.SearchServiceApplication"
            }

            $proxies = Get-SPServiceApplicationProxy
            foreach ($proxyInstance in $proxies)
            {
                if ($serviceApp.IsConnected($proxyInstance))
                {
                    $proxyInstance.Delete()
                }
            }

            Remove-SPServiceApplication -Identity $serviceApp -Confirm:$false
        }
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    Write-Verbose -Message "Testing Search service application '$Name'"

    $PSBoundParameters.Ensure = $Ensure

    if ($UseSQLAuthentication -eq $true)
    {
        Write-Verbose ("Cannot check Farm Account permissions when SQL " + `
                "DatabaseCredentials are specified.")
        Write-Verbose "Setting FixFarmAccountPermissions to False"
        $PSBoundParameters.FixFarmAccountPermissions = $false
    }
    else
    {
        $PSBoundParameters.FixFarmAccountPermissions = $FixFarmAccountPermissions
    }

    $CurrentValues = Get-TargetResource @PSBoundParameters

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

    if ($PSBoundParameters.ContainsKey("DefaultContentAccessAccount") `
            -and $Ensure -eq "Present")
    {
        $desired = $DefaultContentAccessAccount.UserName
        $current = $CurrentValues.DefaultContentAccessAccount.UserName

        if ($desired -ne $current)
        {
            $message = ("Specified Default content access account is not in the desired state" + `
                    "Actual: $current Desired: $desired")
            Write-Verbose -Message $message
            Add-SPDscEvent -Message $message -EntryType 'Error' -EventID 1 -Source $MyInvocation.MyCommand.Source
            return $false
        }
    }

    if ($FixFarmAccountPermissions -eq $true)
    {
        if ($CurrentValues.FixFarmAccountPermissions -eq $true)
        {
            $message = ("FixFarmAccountPermissions is set to True, but the Search databases " + `
                    "do not have the correct permissions")
            Write-Verbose -Message $message
            Add-SPDscEvent -Message $message -EntryType 'Error' -EventID 1 -Source $MyInvocation.MyCommand.Source
            return $false
        }
    }

    if ($Ensure -eq "Present")
    {
        $result = Test-SPDscParameterState -CurrentValues $CurrentValues `
            -Source $($MyInvocation.MyCommand.Source) `
            -DesiredValues $PSBoundParameters `
            -ValuesToCheck @("Ensure",
            "ApplicationPool",
            "SearchCenterUrl",
            "ProxyName",
            "AlertsEnabled")
    }
    else
    {
        $result = Test-SPDscParameterState -CurrentValues $CurrentValues `
            -Source $($MyInvocation.MyCommand.Source) `
            -DesiredValues $PSBoundParameters `
            -ValuesToCheck @("Ensure")
    }

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

    return $result
}

function Export-TargetResource
{
    $VerbosePreference = "SilentlyContinue"
    $searchSA = Get-SPServiceApplication | Where-Object { $_.GetType().Name -eq "SearchServiceApplication" }

    $i = 1
    $total = $searchSA.Length
    $content = ''
    $ParentModuleBase = Get-Module "SharePointDsc" -ListAvailable | Select-Object -ExpandProperty Modulebase
    $module = Join-Path -Path $ParentModuleBase -ChildPath "\DSCResources\MSFT_SPSearchServiceApp\MSFT_SPSearchServiceApp.psm1" -Resolve

    foreach ($searchSAInstance in $searchSA)
    {
        try
        {
            if ($null -ne $searchSAInstance)
            {
                $serviceName = $searchSAInstance.Name
                Write-Host "Scanning Search Service Application [$i/$total] {$serviceName}"
                $params = Get-DSCFakeParameters -ModulePath $module

                $partialContent = " SPSearchServiceApp " + $searchSAInstance.Name.Replace(" ", "") + "`r`n"
                $partialContent += " {`r`n"
                $params.Name = $serviceName
                $params.ApplicationPool = $searchSAInstance.ApplicationPool.Name
                $results = Get-TargetResource @params
                if ($results.Get_Item("CloudIndex") -eq $false)
                {
                    $results.Remove("CloudIndex")
                }

                if ($results.Contains("InstallAccount"))
                {
                    $results.Remove("InstallAccount")
                }

                if ($null -eq $results.SearchCenterUrl)
                {
                    $results.Remove("SearchCenterUrl")
                }

                if ($null -eq $results["DefaultContentAccessAccount"])
                {
                    $results.Remove("DefaultContentAccessAccount")
                }
                else
                {
                    Save-Credentials -UserName $results["DefaultContentAccessAccount"].Username
                    $results["DefaultContentAccessAccount"] = Resolve-Credentials -UserName $results["DefaultContentAccessAccount"].Username
                }

                $results = Repair-Credentials -results $results

                Add-ConfigurationDataEntry -Node "NonNodeData" -Key "DatabaseServer" -Value $results.DatabaseServer -Description "Name of the Database Server associated with the destination SharePoint Farm;"
                $results.DatabaseServer = "`$ConfigurationData.NonNodeData.DatabaseServer"

                $currentBlock = Get-DSCBlock -Params $results -ModulePath $module
                if ($results.ContainsKey("DefaultContentAccessAccount"))
                {
                    $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "DefaultContentAccessAccount"
                }
                $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "DatabaseServer"
                $currentBlock = Convert-DSCStringParamToVariable -DSCBlock $currentBlock -ParameterName "PsDscRunAsCredential"
                $partialContent += $currentBlock
                $partialContent += " }`r`n"

                $properties = @{
                    searchSAName = $searchSAInstance.Name
                    DependsOn    = "[SPSearchServiceApp]$($searchSAInstance.Name.Replace(' ', ''))"
                }
                $partialContent += Read-TargetResource -ResourceName 'SPSearchContentSource' -ExportParams $properties
            }
            $i++
            $content += $partialContent
        }
        catch
        {
            $_
            $Global:ErrorLog += "[Search Service Application]" + $searchSAInstance.Name + "`r`n"
            $Global:ErrorLog += "$_`r`n`r`n"
        }
    }
    return $content
}

Export-ModuleMember -Function *-TargetResource