-
Notifications
You must be signed in to change notification settings - Fork 225
/
SqlServerDsc.Common.psm1
2428 lines (1988 loc) · 75.1 KB
/
SqlServerDsc.Common.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
$script:resourceHelperModulePath = Join-Path -Path $PSScriptRoot -ChildPath '..\..\Modules\DscResource.Common'
Import-Module -Name $script:resourceHelperModulePath
$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US'
<#
.SYNOPSIS
Returns the value of the provided Name parameter at the registry
location provided in the Path parameter.
.PARAMETER Path
Specifies the path in the registry to the property name.
.PARAMETER PropertyName
Specifies the the name of the property to return the value for.
#>
function Get-RegistryPropertyValue
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path,
[Parameter(Mandatory = $true)]
[System.String]
$Name
)
$getItemPropertyParameters = @{
Path = $Path
Name = $Name
}
<#
Using a try/catch block instead of 'SilentlyContinue' to be
able to unit test a failing registry path.
#>
try
{
$getItemPropertyResult = (Get-ItemProperty @getItemPropertyParameters -ErrorAction 'Stop').$Name
}
catch
{
$getItemPropertyResult = $null
}
return $getItemPropertyResult
}
<#
.SYNOPSIS
Returns the value of the provided in the Name parameter, at the registry
location provided in the Path parameter.
.PARAMETER Path
String containing the path in the registry to the property name.
.PARAMETER PropertyName
String containing the name of the property for which the value is returned.
#>
function Format-Path
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Path,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$TrailingSlash
)
# Remove trailing slash ('\') from path.
if ($TrailingSlash.IsPresent)
{
<#
Trim backslash, but only if the path contains a full path and
not just a qualifier.
#>
if ($Path -notmatch '^[a-zA-Z]:\\$')
{
$Path = $Path.TrimEnd('\')
}
<#
If the path only contains a qualifier but no backslash ('M:'),
then a backslash is added ('M:\').
#>
if ($Path -match '^[a-zA-Z]:$')
{
$Path = '{0}\' -f $Path
}
}
return $Path
}
<#
.SYNOPSIS
Copy folder structure using Robocopy. Every file and folder, including empty ones are copied.
.PARAMETER Path
Source path to be copied.
.PARAMETER DestinationPath
The path to the destination.
#>
function Copy-ItemWithRobocopy
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Path,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$DestinationPath
)
$quotedPath = '"{0}"' -f $Path
$quotedDestinationPath = '"{0}"' -f $DestinationPath
$robocopyExecutable = Get-Command -Name "Robocopy.exe" -ErrorAction Stop
$robocopyArgumentSilent = '/njh /njs /ndl /nc /ns /nfl'
$robocopyArgumentCopySubDirectoriesIncludingEmpty = '/e'
$robocopyArgumentDeletesDestinationFilesAndDirectoriesNotExistAtSource = '/purge'
if ([System.Version]$robocopyExecutable.FileVersionInfo.ProductVersion -ge [System.Version]'6.3.9600.16384')
{
Write-Verbose -Message $script:localizedData.RobocopyUsingUnbufferedIo -Verbose
$robocopyArgumentUseUnbufferedIO = '/J'
}
else
{
Write-Verbose -Message $script:localizedData.RobocopyNotUsingUnbufferedIo -Verbose
}
$robocopyArgumentList = '{0} {1} {2} {3} {4} {5}' -f @(
$quotedPath,
$quotedDestinationPath,
$robocopyArgumentCopySubDirectoriesIncludingEmpty,
$robocopyArgumentDeletesDestinationFilesAndDirectoriesNotExistAtSource,
$robocopyArgumentUseUnbufferedIO,
$robocopyArgumentSilent
)
$robocopyStartProcessParameters = @{
FilePath = $robocopyExecutable.Name
ArgumentList = $robocopyArgumentList
}
Write-Verbose -Message ($script:localizedData.RobocopyArguments -f $robocopyArgumentList) -Verbose
$robocopyProcess = Start-Process @robocopyStartProcessParameters -Wait -NoNewWindow -PassThru
switch ($($robocopyProcess.ExitCode))
{
{ $_ -in 8, 16 }
{
$errorMessage = $script:localizedData.RobocopyErrorCopying -f $_
New-InvalidOperationException -Message $errorMessage
}
{ $_ -gt 7 }
{
$errorMessage = $script:localizedData.RobocopyFailuresCopying -f $_
New-InvalidResultException -Message $errorMessage
}
1
{
Write-Verbose -Message $script:localizedData.RobocopySuccessful -Verbose
}
2
{
Write-Verbose -Message $script:localizedData.RobocopyRemovedExtraFilesAtDestination -Verbose
}
3
{
Write-Verbose -Message (
'{0} {1}' -f $script:localizedData.RobocopySuccessful, $script:localizedData.RobocopyRemovedExtraFilesAtDestination
) -Verbose
}
{ $_ -eq 0 -or $null -eq $_ }
{
Write-Verbose -Message $script:localizedData.RobocopyAllFilesPresent -Verbose
}
}
}
<#
.SYNOPSIS
Connects to the source using the provided credentials and then uses
robocopy to download the installation media to a local temporary folder.
.PARAMETER SourcePath
Source path to be copied.
.PARAMETER SourceCredential
The credentials to access the SourcePath.
.PARAMETER PassThru
If used, returns the destination path as string.
.OUTPUTS
Returns the destination path (when used with the parameter PassThru).
#>
function Invoke-InstallationMediaCopy
{
[CmdletBinding()]
[OutputType([System.String])]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$SourcePath,
[Parameter(Mandatory = $true)]
[System.Management.Automation.PSCredential]
$SourceCredential,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$PassThru
)
Connect-UncPath -RemotePath $SourcePath -SourceCredential $SourceCredential
$SourcePath = $SourcePath.TrimEnd('/\')
<#
Create a destination folder so the media files aren't written
to the root of the Temp folder.
#>
$serverName, $shareName, $leafs = ($SourcePath -replace '\\\\') -split '\\'
if ($leafs)
{
$mediaDestinationFolder = $leafs | Select-Object -Last 1
}
else
{
$mediaDestinationFolder = New-Guid | Select-Object -ExpandProperty Guid
}
$mediaDestinationPath = Join-Path -Path (Get-TemporaryFolder) -ChildPath $mediaDestinationFolder
Write-Verbose -Message ($script:localizedData.RobocopyIsCopying -f $SourcePath, $mediaDestinationPath) -Verbose
Copy-ItemWithRobocopy -Path $SourcePath -DestinationPath $mediaDestinationPath
Disconnect-UncPath -RemotePath $SourcePath
if ($PassThru.IsPresent)
{
return $mediaDestinationPath
}
}
<#
.SYNOPSIS
Connects to the UNC path provided in the parameter SourcePath.
Optionally connects using the provided credentials.
.PARAMETER SourcePath
Source path to connect to.
.PARAMETER SourceCredential
The credentials to access the path provided in SourcePath.
.PARAMETER PassThru
If used, returns a MSFT_SmbMapping object that represents the newly
created SMB mapping.
.OUTPUTS
Returns a MSFT_SmbMapping object that represents the newly created
SMB mapping (ony when used with parameter PassThru).
#>
function Connect-UncPath
{
[CmdletBinding()]
[OutputType([Microsoft.Management.Infrastructure.CimInstance])]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$RemotePath,
[Parameter()]
[System.Management.Automation.PSCredential]
$SourceCredential,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$PassThru
)
$newSmbMappingParameters = @{
RemotePath = $RemotePath
}
if ($PSBoundParameters.ContainsKey('SourceCredential'))
{
$newSmbMappingParameters['UserName'] = $SourceCredential.UserName
$newSmbMappingParameters['Password'] = $SourceCredential.GetNetworkCredential().Password
}
$newSmbMappingResult = New-SmbMapping @newSmbMappingParameters
if ($PassThru.IsPresent)
{
return $newSmbMappingResult
}
}
<#
.SYNOPSIS
Disconnects from the UNC path provided in the parameter SourcePath.
.PARAMETER SourcePath
Source path to disconnect from.
#>
function Disconnect-UncPath
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$RemotePath
)
Remove-SmbMapping -RemotePath $RemotePath -Force
}
<#
.SYNOPSIS
Queries the registry and returns $true if there is a pending reboot.
.OUTPUTS
Returns $true if there is a pending reboot, otherwise it returns $false.
#>
function Test-PendingRestart
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
)
$getRegistryPropertyValueParameters = @{
Path = 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager'
Name = 'PendingFileRenameOperations'
}
<#
If the key 'PendingFileRenameOperations' does not exist then if should
return $false, otherwise it should return $true.
#>
return $null -ne (Get-RegistryPropertyValue @getRegistryPropertyValueParameters)
}
<#
.SYNOPSIS
Starts the SQL setup process.
.PARAMETER FilePath
String containing the path to setup.exe.
.PARAMETER ArgumentList
The arguments that should be passed to setup.exe.
.PARAMETER Timeout
The timeout in seconds to wait for the process to finish.
#>
function Start-SqlSetupProcess
{
param
(
[Parameter(Mandatory = $true)]
[System.String]
$FilePath,
[Parameter()]
[System.String]
$ArgumentList,
[Parameter(Mandatory = $true)]
[System.UInt32]
$Timeout
)
$startProcessParameters = @{
FilePath = $FilePath
ArgumentList = $ArgumentList
}
$sqlSetupProcess = Start-Process @startProcessParameters -PassThru -NoNewWindow -ErrorAction Stop
Write-Verbose -Message ($script:localizedData.StartSetupProcess -f $sqlSetupProcess.Id, $startProcessParameters.FilePath, $Timeout) -Verbose
Wait-Process -InputObject $sqlSetupProcess -Timeout $Timeout -ErrorAction Stop
return $sqlSetupProcess.ExitCode
}
<#
.SYNOPSIS
Connect to a SQL Server Database Engine and return the server object.
.PARAMETER ServerName
String containing the host name of the SQL Server to connect to.
Default value is the current computer name.
.PARAMETER InstanceName
String containing the SQL Server Database Engine instance to connect to.
Default value is 'MSSQLSERVER'.
.PARAMETER SetupCredential
The credentials to use to impersonate a user when connecting to the
SQL Server Database Engine instance. If this parameter is left out, then
the current user will be used to connect to the SQL Server Database Engine
instance using Windows Integrated authentication.
.PARAMETER LoginType
Specifies which type of logon credential should be used. The valid types
are 'WindowsUser' or 'SqlLogin'. Default value is 'WindowsUser'
If set to 'WindowsUser' then the it will impersonate using the Windows
login specified in the parameter SetupCredential.
If set to 'WindowsUser' then the it will impersonate using the native SQL
login specified in the parameter SetupCredential.
.PARAMETER StatementTimeout
Set the query StatementTimeout in seconds. Default 600 seconds (10 minutes).
.EXAMPLE
Connect-SQL
Connects to the default instance on the local server.
.EXAMPLE
Connect-SQL -InstanceName 'MyInstance'
Connects to the instance 'MyInstance' on the local server.
.EXAMPLE
Connect-SQL ServerName 'sql.company.local' -InstanceName 'MyInstance' -ErrorAction 'Stop'
Connects to the instance 'MyInstance' on the server 'sql.company.local'.
#>
function Connect-SQL
{
[CmdletBinding(DefaultParameterSetName = 'SqlServer')]
param
(
[Parameter(ParameterSetName = 'SqlServer')]
[Parameter(ParameterSetName = 'SqlServerWithCredential')]
[ValidateNotNull()]
[System.String]
$ServerName = (Get-ComputerName),
[Parameter(ParameterSetName = 'SqlServer')]
[Parameter(ParameterSetName = 'SqlServerWithCredential')]
[ValidateNotNull()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter(ParameterSetName = 'SqlServerWithCredential', Mandatory = $true)]
[ValidateNotNull()]
[Alias('SetupCredential', 'DatabaseCredential')]
[System.Management.Automation.PSCredential]
$Credential,
[Parameter(ParameterSetName = 'SqlServerWithCredential')]
[ValidateSet('WindowsUser', 'SqlLogin')]
[System.String]
$LoginType = 'WindowsUser',
[Parameter()]
[ValidateNotNull()]
[System.Int32]
$StatementTimeout = 600
)
Import-SqlDscPreferredModule
if ($InstanceName -eq 'MSSQLSERVER')
{
$databaseEngineInstance = $ServerName
}
else
{
$databaseEngineInstance = '{0}\{1}' -f $ServerName, $InstanceName
}
$sqlServerObject = New-Object -TypeName 'Microsoft.SqlServer.Management.Smo.Server'
$sqlConnectionContext = $sqlServerObject.ConnectionContext
$sqlConnectionContext.ServerInstance = $databaseEngineInstance
$sqlConnectionContext.StatementTimeout = $StatementTimeout
$sqlConnectionContext.ApplicationName = 'SqlServerDsc'
if ($PSCmdlet.ParameterSetName -eq 'SqlServer')
{
<#
This is only used for verbose messaging and not for the connection
string since this is using Integrated Security=true (SSPI).
#>
$connectUserName = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
Write-Verbose -Message (
$script:localizedData.ConnectingUsingIntegrated -f $connectUsername
) -Verbose
}
else
{
$connectUserName = $Credential.UserName
Write-Verbose -Message (
$script:localizedData.ConnectingUsingImpersonation -f $connectUsername, $LoginType
) -Verbose
if ($LoginType -eq 'SqlLogin')
{
$sqlConnectionContext.LoginSecure = $false
$sqlConnectionContext.Login = $connectUserName
$sqlConnectionContext.SecurePassword = $Credential.Password
}
if ($LoginType -eq 'WindowsUser')
{
$sqlConnectionContext.LoginSecure = $true
$sqlConnectionContext.ConnectAsUser = $true
$sqlConnectionContext.ConnectAsUserName = $connectUserName
$sqlConnectionContext.ConnectAsUserPassword = $Credential.GetNetworkCredential().Password
}
}
try
{
$sqlConnectionContext.Connect()
$instanceStatus = $sqlServerObject.Status
if ($instanceStatus)
{
# Property Status is of type Enum ServerStatus, we return the string equivalent.
$instanceStatus = $instanceStatus.ToString()
}
if ($instanceStatus -match '^Online$')
{
Write-Verbose -Message (
$script:localizedData.ConnectedToDatabaseEngineInstance -f $databaseEngineInstance
) -Verbose
return $sqlServerObject
}
else
{
if ([System.String]::IsNullOrEmpty($instanceStatus))
{
$instanceStatus = 'Unknown'
}
$errorMessage = $script:localizedData.DatabaseEngineInstanceNotOnline -f @(
$databaseEngineInstance,
$instanceStatus
)
$invalidOperationException = New-Object -TypeName 'InvalidOperationException' -ArgumentList @($errorMessage)
$newObjectParameters = @{
TypeName = 'System.Management.Automation.ErrorRecord'
ArgumentList = @(
$invalidOperationException.ToString(),
'CS0001',
'InvalidOperation',
$databaseEngineInstance
)
}
$errorRecordToThrow = New-Object @newObjectParameters
Write-Error -ErrorRecord $errorRecordToThrow
}
}
catch
{
$errorMessage = $script:localizedData.FailedToConnectToDatabaseEngineInstance -f $databaseEngineInstance
$invalidOperationException = New-Object -TypeName 'InvalidOperationException' -ArgumentList @($errorMessage, $_.Exception)
$newObjectParameters = @{
TypeName = 'System.Management.Automation.ErrorRecord'
ArgumentList = @(
$invalidOperationException.ToString(),
'CS0002',
'InvalidOperation',
$databaseEngineInstance
)
}
$errorRecordToThrow = New-Object @newObjectParameters
Write-Error -ErrorRecord $errorRecordToThrow
}
finally
{
<#
Connect will ensure we actually can connect, but we need to disconnect
from the session so we don't have anything hanging. If we need run a
method on the returned $sqlServerObject it will automatically open a
new session and then close, therefore we don't need to keep this
session open.
#>
$sqlConnectionContext.Disconnect()
}
}
<#
.SYNOPSIS
Connect to a SQL Server Analysis Service and return the server object.
.PARAMETER ServerName
String containing the host name of the SQL Server to connect to.
.PARAMETER InstanceName
String containing the SQL Server Analysis Service instance to connect to.
.PARAMETER SetupCredential
PSCredential object with the credentials to use to impersonate a user when
connecting. If this is not provided then the current user will be used to
connect to the SQL Server Analysis Service instance.
#>
function Connect-SQLAnalysis
{
[CmdletBinding()]
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$ServerName = (Get-ComputerName),
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$SetupCredential,
[Parameter()]
[System.String[]]
$FeatureFlag
)
if ($InstanceName -eq 'MSSQLSERVER')
{
$analysisServiceInstance = $ServerName
}
else
{
$analysisServiceInstance = "$ServerName\$InstanceName"
}
if ($SetupCredential)
{
$userName = $SetupCredential.UserName
$password = $SetupCredential.GetNetworkCredential().Password
$analysisServicesDataSource = "Data Source=$analysisServiceInstance;User ID=$userName;Password=$password"
}
else
{
$analysisServicesDataSource = "Data Source=$analysisServiceInstance"
}
try
{
if ((Test-FeatureFlag -FeatureFlag $FeatureFlag -TestFlag 'AnalysisServicesConnection'))
{
Import-SqlDscPreferredModule
$analysisServicesObject = New-Object -TypeName 'Microsoft.AnalysisServices.Server'
if ($analysisServicesObject)
{
$analysisServicesObject.Connect($analysisServicesDataSource)
}
if ((-not $analysisServicesObject) -or ($analysisServicesObject -and $analysisServicesObject.Connected -eq $false))
{
$errorMessage = $script:localizedData.FailedToConnectToAnalysisServicesInstance -f $analysisServiceInstance
New-InvalidOperationException -Message $errorMessage
}
else
{
Write-Verbose -Message ($script:localizedData.ConnectedToAnalysisServicesInstance -f $analysisServiceInstance) -Verbose
}
}
else
{
$null = Import-Assembly -Name 'Microsoft.AnalysisServices' -LoadWithPartialName
$analysisServicesObject = New-Object -TypeName 'Microsoft.AnalysisServices.Server'
if ($analysisServicesObject)
{
$analysisServicesObject.Connect($analysisServicesDataSource)
}
else
{
$errorMessage = $script:localizedData.FailedToConnectToAnalysisServicesInstance -f $analysisServiceInstance
New-InvalidOperationException -Message $errorMessage
}
Write-Verbose -Message ($script:localizedData.ConnectedToAnalysisServicesInstance -f $analysisServiceInstance) -Verbose
}
}
catch
{
$errorMessage = $script:localizedData.FailedToConnectToAnalysisServicesInstance -f $analysisServiceInstance
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
return $analysisServicesObject
}
<#
.SYNOPSIS
Imports the assembly into the session.
.DESCRIPTION
Imports the assembly into the session and returns a reference to the
assembly.
.PARAMETER Name
Specifies the name of the assembly to load.
.PARAMETER LoadWithPartialName
Specifies if the imported assembly should be the first found in GAC,
regardless of version.
.OUTPUTS
[System.Reflection.Assembly]
Returns a reference to the assembly object.
.EXAMPLE
Import-Assembly -Name "Microsoft.SqlServer.ConnectionInfo, Version=$SqlMajorVersion.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91"
.EXAMPLE
Import-Assembly -Name 'Microsoft.AnalysisServices' -LoadWithPartialName
.NOTES
This should normally work using Import-Module and New-Object instead of
using the method [System.Reflection.Assembly]::Load(). But due to a
missing assembly in the module SqlServer this is still needed.
Import-Module SqlServer
$connectionInfo = New-Object -TypeName 'Microsoft.SqlServer.Management.Common.ServerConnection' -ArgumentList @('testclu01a\SQL2014')
# Missing assembly 'Microsoft.SqlServer.Rmo' in module SqlServer prevents this call from working.
$replication = New-Object -TypeName 'Microsoft.SqlServer.Replication.ReplicationServer' -ArgumentList @($connectionInfo)
#>
function Import-Assembly
{
[CmdletBinding()]
[OutputType([System.Reflection.Assembly])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$Name,
[Parameter()]
[System.Management.Automation.SwitchParameter]
$LoadWithPartialName
)
try
{
if ($LoadWithPartialName.IsPresent)
{
$assemblyInformation = [System.Reflection.Assembly]::LoadWithPartialName($Name)
}
else
{
$assemblyInformation = [System.Reflection.Assembly]::Load($Name)
}
Write-Verbose -Message (
$script:localizedData.LoadedAssembly -f $assemblyInformation.FullName
)
}
catch
{
$errorMessage = $script:localizedData.FailedToLoadAssembly -f $Name
New-InvalidOperationException -Message $errorMessage -ErrorRecord $_
}
return $assemblyInformation
}
<#
.SYNOPSIS
Returns the major SQL version for the specific instance.
.PARAMETER InstanceName
String containing the name of the SQL instance to be configured. Default
value is 'MSSQLSERVER'.
.OUTPUTS
System.UInt16. Returns the SQL Server major version number.
#>
function Get-SqlInstanceMajorVersion
{
[CmdletBinding()]
[OutputType([System.UInt16])]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$InstanceName
)
$sqlInstanceId = (Get-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL').$InstanceName
$sqlVersion = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server\$sqlInstanceId\Setup").Version
if (-not $sqlVersion)
{
$errorMessage = $script:localizedData.SqlServerVersionIsInvalid -f $InstanceName
New-InvalidResultException -Message $errorMessage
}
[System.UInt16] $sqlMajorVersionNumber = $sqlVersion.Split('.')[0]
return $sqlMajorVersionNumber
}
<#
.SYNOPSIS
Restarts a SQL Server instance and associated services
.PARAMETER ServerName
Hostname of the SQL Server to be configured
.PARAMETER InstanceName
Name of the SQL instance to be configured. Default is 'MSSQLSERVER'
.PARAMETER Timeout
Timeout value for restarting the SQL services. The default value is 120 seconds.
.PARAMETER SkipClusterCheck
If cluster check should be skipped. If this is present no connection
is made to the instance to check if the instance is on a cluster.
This need to be used for some resource, for example for the SqlServerNetwork
resource when it's used to enable a disable protocol.
.PARAMETER SkipWaitForOnline
If this is present no connection is made to the instance to check if the
instance is online.
This need to be used for some resource, for example for the SqlServerNetwork
resource when it's used to disable protocol.
.PARAMETER OwnerNode
Specifies a list of owner nodes names of a cluster groups. If the SQL Server
instance is a Failover Cluster instance then the cluster group will only
be taken offline and back online when the owner of the cluster group is
one of the nodes specified in this list. These node names specified in this
parameter must match the Owner property of the cluster resource, for example
@('sqltest10', 'SQLTEST11'). The names are case-insensitive.
If this parameter is not specified the cluster group will be taken offline
and back online regardless of owner.
.EXAMPLE
Restart-SqlService -ServerName localhost
.EXAMPLE
Restart-SqlService -ServerName localhost -InstanceName 'NamedInstance'
.EXAMPLE
Restart-SqlService -ServerName localhost -InstanceName 'NamedInstance' -SkipClusterCheck -SkipWaitForOnline
.EXAMPLE
Restart-SqlService -ServerName CLU01 -Timeout 300
.EXAMPLE
Restart-SqlService -ServerName CLU01 -Timeout 300 -OwnerNode 'testclu10'
#>
function Restart-SqlService
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[System.String]
$ServerName,
[Parameter()]
[System.String]
$InstanceName = 'MSSQLSERVER',
[Parameter()]
[System.UInt32]
$Timeout = 120,
[Parameter()]
[Switch]
$SkipClusterCheck,
[Parameter()]
[Switch]
$SkipWaitForOnline,
[Parameter()]
[System.String[]]
$OwnerNode
)
$restartWindowsService = $true
# Check if a cluster, otherwise assume that a Windows service should be restarted.
if (-not $SkipClusterCheck.IsPresent)
{
## Connect to the instance
$serverObject = Connect-SQL -ServerName $ServerName -InstanceName $InstanceName -ErrorAction 'Stop'
if ($serverObject.IsClustered)
{
# Make sure Windows service is not restarted outside of the cluster.
$restartWindowsService = $false
$restartSqlClusterServiceParameters = @{
InstanceName = $serverObject.ServiceName
}
if ($PSBoundParameters.ContainsKey('Timeout'))
{
$restartSqlClusterServiceParameters['Timeout'] = $Timeout
}
if ($PSBoundParameters.ContainsKey('OwnerNode'))
{
$restartSqlClusterServiceParameters['OwnerNode'] = $OwnerNode
}
Restart-SqlClusterService @restartSqlClusterServiceParameters
}
}
if ($restartWindowsService)
{
if ($InstanceName -eq 'MSSQLSERVER')
{
$serviceName = 'MSSQLSERVER'
}
else
{
$serviceName = 'MSSQL${0}' -f $InstanceName
}
Write-Verbose -Message ($script:localizedData.GetServiceInformation -f 'SQL Server') -Verbose
$sqlService = Get-Service -Name $serviceName
<#
Get all dependent services that are running.
There are scenarios where an automatic service is stopped and should not be restarted automatically.
#>
$agentService = $sqlService.DependentServices |
Where-Object -FilterScript { $_.Status -eq 'Running' }
# Restart the SQL Server service
Write-Verbose -Message ($script:localizedData.RestartService -f 'SQL Server') -Verbose
$sqlService |