This repository was archived by the owner on Mar 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPureStorageDbaTools.psm1
1026 lines (868 loc) · 45.6 KB
/
PureStorageDbaTools.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
function New-PfaDbSnapshot
{
<#
.SYNOPSIS
A PowerShell function to create a FlashArray snapshot of the volume that a database resides on.
.DESCRIPTION
A PowerShell function to create a FlashArray snapshot of the volume that a database resides on, based in the
values of the following parameters:
.PARAMETER Database
The name of the database to refresh, note that it is assumed that source and target database(s) are named the same.
This parameter is MANDATORY.
.PARAMETER SqlInstance
This can be one or multiple SQL Server instance(s) that host the database(s) to be refreshed, in the case that the
function is invoked to refresh databases across more than one instance, the list of target instances should be
spedcified as an array of strings, otherwise a single string representing the target instance will suffice. This
parameter is MANDATORY.
.PARAMETER PfaEndpoint
The ip address representing the FlashArray that the volumes for the source and refresh target databases reside on.
This parameter is MANDATORY.
.PARAMETER PfaCredentials
A PSCredential object containing the username and password of the FlashArray to connect to. For instruction on how
to store and retrieve these from an encrypted file, refer to this article https://www.purepowershellguy.com/?p=8431
.EXAMPLE
New-PfaDbSnapshot -Database tpch-no-compression
-SqlInstance z-sql2016-devops-prd
-PfaEndpoint 10.225.112.10
-PfaCredentials $Cred
Create a snapshot of FlashArray volume that stores the tpch-no-compression database on the z-sql2016-devops-prd instance
-RefreshSource parameter.
.NOTES
Known Restrictions
------------------
1. This function does not currently work for databases associated with
failover cluster instances.
2. This function cannot be used to seed secondary replicas in availability
groups using databases in the primary replica.
3. The function assumes that all database files and the transaction log
reside on a single FlashArray volume.
Obtaining The PureStorageDbaTools Module
----------------------------------------
This function is part of the PureStorageDbaTools module, it is recommend
that the module is always obtained from the PowerShell gallery:
https://www.powershellgallery.com/packages/PureStorageDbaTools
Note that it has dependencies on the dbatools and PureStoragePowerShellSDK
modules which are installed as part of the installation of this module.
Licence
-------
This function is available under the Apache 2.0 license, stipulated as follows:
Copyright 2017 Pure Storage, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.LINK
https://www.powershellgallery.com/packages/PureStorageDbaTools
https://www.purepowershellguy.com/?p=8431
Invoke-PfaDbaRefresh
Enable-DataMasks
#>
param(
[parameter(mandatory=$true)] [string] $Database
,[parameter(mandatory=$true)] [string] $SqlInstance
,[parameter(mandatory=$true)] [string] $PfaEndpoint
,[parameter(mandatory=$true)] [System.Management.Automation.PSCredential] $PfaCredentials
)
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if ( ! $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) ) {
Write-Error "This function needs to be invoked within a PowerShell session with elevated admin rights"
Return
}
try {
$FlashArray = New-PfaArray -EndPoint $PfaEndpoint -Credentials $PfaCredentials -IgnoreCertificateError
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to connect to FlashArray endpoint $PfaEndpoint with: $ExceptionMessage"
Return
}
Write-Colour -Text "FlashArray endpoint : ", "CONNECTED" -Color Yellow, Green
try {
$DestDb = Get-DbaDatabase -sqlinstance $SqlInstance -Database $Database
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to connect to destination database $SqlInstance.$Database with: $ExceptionMessage"
Return
}
Write-Colour -Text "Target SQL Server instance: ", $SqlInstance, " - ", "CONNECTED" -Color Yellow, Green, Green, Green
Write-Colour -Text "Target windows drive : ", $DestDb.PrimaryFilePath.Split(':')[0] -Color Yellow, Green
try {
$TargetServer = (Connect-DbaInstance -SqlInstance $SqlInstance).ComputerNamePhysicalNetBIOS
}
catch {
Write-Error "Failed to determine target server name with: $ExceptionMessage"
}
Write-Colour -Text "Target SQL Server host : ", $TargetServer -ForegroundColor Yellow, Green
$GetDbDisk = { param ( $Db )
$DbDisk = Get-Partition -DriveLetter $Db.PrimaryFilePath.Split(':')[0]| Get-Disk
return $DbDisk
}
try {
$TargetDisk = Invoke-Command -ComputerName $TargetServer -ScriptBlock $GetDbDisk -ArgumentList $DestDb
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to determine the windows disk snapshot target with: $ExceptionMessage"
Return
}
Write-Colour -Text "Target disk serial number : ", $TargetDisk.SerialNumber -Color Yellow, Green
try {
$TargetVolume = Get-PfaVolumes -Array $FlashArray | Where-Object { $_.serial -eq $TargetDisk.SerialNumber } | Select-Object name
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to determine snapshot FlashArray volume with: $ExceptionMessage"
Return
}
$SnapshotSuffix = $SqlInstance.Replace('\', '-') + '-' + $Database + '-' + $(Get-Date).Hour + $(Get-Date).Minute + $(Get-Date).Second
Write-Colour -Text "Snapshot target Pfa volume: ", $TargetVolume.name -Color Yellow, Green
Write-Colour -Text "Snapshot suffix : ", $SnapshotSuffix -Color Yellow, Green
try {
New-PfaVolumeSnapshots -Array $FlashArray -Sources $TargetVolume.name -Suffix $SnapshotSuffix
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to create snapshot for target database FlashArray volume with: $ExceptionMessage"
Return
}
}
function DbRefresh
{
param(
[parameter(mandatory=$true)] [string] $DestSqlInstance
,[parameter(mandatory=$true)] [string] $RefreshDatabase
,[parameter(mandatory=$true)] [string] $PfaEndpoint
,[parameter(mandatory=$true)] [System.Management.Automation.PSCredential] $PfaCredentials
,[parameter(mandatory=$true)] [string] $SourceVolume
,[parameter(mandatory=$false)] [string] $StaticDataMaskFile
,[parameter(mandatory=$false)] [bool] $ForceDestDbOffline
,[parameter(mandatory=$false)] [bool] $NoPsRemoting
,[parameter(mandatory=$false)] [bool] $PromptForSnapshot
,[parameter(mandatory=$false)] [bool] $ApplyDataMasks
)
try {
$FlashArray = New-PfaArray -EndPoint $PfaEndpoint -Credentials $PfaCredentials -IgnoreCertificateError
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to connect to FlashArray endpoint $PfaEndpoint with: $ExceptionMessage"
Return
}
try {
$DestDb = Get-DbaDatabase -sqlinstance $DestSqlInstance -Database $RefreshDatabase
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to connect to destination database $DestSqlInstance.$Database with: $ExceptionMessage"
Return
}
Write-Host " "
Write-Colour -Text "Target SQL Server instance: ", $DestSqlInstance, "- CONNECTED" -ForegroundColor Yellow, Green, Green
try {
$TargetServer = (Connect-DbaInstance -SqlInstance $DestSqlInstance).ComputerNamePhysicalNetBIOS
}
catch {
Write-Error "Failed to determine target server name with: $ExceptionMessage"
}
Write-Colour -Text "Target SQL Server host : ", $TargetServer -ForegroundColor Yellow, Green
$GetDbDisk = { param ( $Db )
$DbDisk = Get-Partition -DriveLetter $Db.PrimaryFilePath.Split(':')[0]| Get-Disk
return $DbDisk
}
$GetVolumeLabel = { param ( $Db )
Write-Verbose "Target database drive letter = $Db.PrimaryFilePath.Split(':')[0]"
$VolumeLabel = $(Get-Volume -DriveLetter $Db.PrimaryFilePath.Split(':')[0]).FileSystemLabel
Write-Verbose "Target database windows volume label = <$VolumeLabel>"
return $VolumeLabel
}
try {
if ( $NoPsRemoting ) {
$DestDisk = Invoke-Command -ScriptBlock $GetDbDisk -ArgumentList $DestDb
$DestVolumeLabel = Invoke-Command -ScriptBlock $GetVolumeLabel -ArgumentList $DestDb
}
else {
$DestDisk = Invoke-Command -ComputerName $TargetServer -ScriptBlock $GetDbDisk -ArgumentList $DestDb
$DestVolumeLabel = Invoke-Command -ComputerName $TargetServer -ScriptBlock $GetVolumeLabel -ArgumentList $DestDb
}
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to determine destination database disk with: $ExceptionMessage"
Return
}
Write-Colour -Text "Target drive letter : ", $DestDb.PrimaryFilePath.Split(':')[0] -ForegroundColor Yellow, Green
try {
$DestVolume = Get-PfaVolumes -Array $FlashArray | Where-Object { $_.serial -eq $DestDisk.SerialNumber } | Select-Object name
if (!$DestVolume) {
throw "Failed to determine destination FlashArray volume, check that source and destination volumes are on the SAME array"
}
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to determine destination FlashArray volume with: $ExceptionMessage"
Return
}
Write-Colour -Text "Target Pfa volume : ", $DestVolume.name -ForegroundColor Yellow, Green
$OfflineDestDisk = { param ( $DiskNumber, $Status )
Set-Disk -Number $DiskNumber -IsOffline $Status
}
try {
if ( $ForceDestDbOffline ) {
$ForceDatabaseOffline = "ALTER DATABASE [$RefreshDatabase] SET OFFLINE WITH ROLLBACK IMMEDIATE"
Invoke-DbaQuery -ServerInstance $DestSqlInstance -Database $RefreshDatabase -Query $ForceDatabaseOffline
}
else {
$DestDb.SetOffline()
}
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to offline database $Database with: $ExceptionMessage"
Return
}
Write-Colour -Text "Target database : ", "OFFLINE" -ForegroundColor Yellow, Green
try {
if ( $NoPsRemoting ) {
Invoke-Command -ScriptBlock $OfflineDestDisk -ArgumentList $DestDisk.Number, $True
}
else {
Invoke-Command -ComputerName $TargetServer -ScriptBlock $OfflineDestDisk -ArgumentList $DestDisk.Number, $True
}
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to offline disk with : $ExceptionMessage"
Return
}
Write-Colour -Text "Target windows disk : ", "OFFLINE" -ForegroundColor Yellow, Green
$StartCopyVolMs = Get-Date
try {
Write-Colour -Text "Source Pfa volume : ", $SourceVolume -ForegroundColor Yellow, Green
New-PfaVolume -Array $FlashArray -VolumeName $DestVolume.name -Source $SourceVolume -Overwrite
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to refresh test database volume with : $ExceptionMessage"
Set-Disk -Number $DestDisk.Number -IsOffline $False
$DestDb.SetOnline()
Return
}
Write-Colour -Text "Volume overwrite : ", "SUCCESSFUL" -ForegroundColor Yellow, Green
$EndCopyVolMs = Get-Date
Write-Colour -Text "Overwrite duration (ms) : ", ($EndCopyVolMs - $StartCopyVolMs).TotalMilliseconds -Color Yellow, Green
$SetVolumeLabel = { param ( $Db, $DestVolumeLabel )
Set-Volume -DriveLetter $Db.PrimaryFilePath.Split(':')[0] -NewFileSystemLabel $DestVolumeLabel
}
try {
if ( $NoPsRemoting ) {
Invoke-Command -ScriptBlock $OfflineDestDisk -ArgumentList $DestDisk.Number, $False
Invoke-Command -ScriptBlock $SetVolumeLabel -ArgumentList $DestDb, $DestVolumeLabel
}
else {
Invoke-Command -ComputerName $TargetServer -ScriptBlock $OfflineDestDisk -ArgumentList $DestDisk.Number, $False
Invoke-Command -ComputerName $TargetServer -ScriptBlock $SetVolumeLabel -ArgumentList $DestDb, $DestVolumeLabel
}
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to online disk with : $ExceptionMessage"
Return
}
Write-Colour -Text "Target windows disk : ", "ONLINE" -ForegroundColor Yellow, Green
try {
$DestDb.SetOnline()
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to online database $Database with: $ExceptionMessage"
Return
}
Write-Colour -Text "Target database : ", "ONLINE" -ForegroundColor Yellow, Green
if ( $ApplyDataMasks ) {
Write-Host "Applying SQL Server dynamic data masks to $RefreshDatabase on SQL Server instance $DestSqlInstance" -ForegroundColor Yellow
try {
Invoke-DynamicDataMasking -SqlInstance $DestSqlInstance -Database $RefreshDatabase
Write-Host "SQL Server dynamic data masking has been applied" -ForegroundColor Yellow
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to apply SQL Server dynamic data masks to $Database on $DestSqlInstance with: $ExceptionMessage"
Return
}
}
elseif ([System.IO.File]::Exists($StaticDataMaskFile)) {
Write-Color -Text "Static data mask target : ", $DestSqlInstance, " - ", $RefreshDatabase -Color Yellow, Green, Green, Green
try {
Invoke-StaticDataMasking -SqlInstance $DestSqlInstance -Database $RefreshDatabase -DataMaskFile $StaticDataMaskFile
Write-Color -Text "Static data masking : ", "APPLIED" -ForegroundColor Yellow, Green
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to apply static data masking to $Database on $DestSqlInstance with: $ExceptionMessage"
Return
}
}
Repair-DbaDbOrphanUser -SqlInstance $DestSqlInstance -Database $RefreshDatabase | Out-Null
Write-Color -Text "Orphaned users : ", "REPAIRED" -ForegroundColor Yellow, Green
}
function Invoke-PfaDbRefresh
{
<#
.SYNOPSIS
A PowerShell function to refresh one or more SQL Server databases (the destination) from either a snapshot or
database.
.DESCRIPTION
A PowerShell function to refresh one or more SQL Server databases either from:
- a snapshot specified by its name
- a snapshot picked from a list associated with the volume the source database resides on
- a source database directly
This function will detect and repair orpaned users in refreshed databases and optionally
apply data masking, based on either:
- the dynamic data masking functionality available in SQL Server version 2016 onwards,
- static data masking built into dbatooils from version 0.9.725, refer to https://dbatools.io/mask/
.PARAMETER RefreshDatabase
The name of the database to refresh, note that it is assumed that source and target database(s) are named the same.
This parameter is MANDATORY.
.PARAMETER RefreshSource
If the RefreshFromSnapshot flag is specified, this parameter takes the name of a snapshot, otherwise this takes the
name of the source SQL Server instance. This parameter is MANDATORY.
.PARAMETER DestSqlInstance
This can be one or multiple SQL Server instance(s) that host the database(s) to be refreshed, in the case that the
function is invoked to refresh databases across more than one instance, the list of target instances should be
spedcified as an array of strings, otherwise a single string representing the target instance will suffice. This
parameter is MANDATORY.
.PARAMETER PfaEndpoint
The ip address representing the FlashArray that the volumes for the source and refresh target databases reside on.
This parameter is MANDATORY.
.PARAMETER PfaCredentials
A PSCredential object containing the username and password of the FlashArray to connect to. For instruction on how
to store and retrieve these from an encrypted file, refer to this article https://www.purepowershellguy.com/?p=8431
.PARAMETER PollJobInterval
Interval at which background job status is poll, if this is ommited polling will not take place. Note that this parameter
is not applicable is the PromptForSnapshot switch is specified.
.PARAMETER PromptForSnapshot
This is an optional flag that if specified will result in a list of snapshots being displayed for the database volume on
the FlashArray that the user can select one from. Despite the source of the refresh operation being an existing snapshot
, the source instance still has to be specified by the RefreshSource parameter in order that the function can determine
which FlashArray volume to list existing snapshots for.
.PARAMETER RefreshFromSnapshot
This is an optional flag that if specified causes the function to expect the RefreshSource parameter to be supplied with
the name of an existing snapshot.
.PARAMETER NoPsRemoting
The commands that off and online the windows volumes associated with the refresh target databases will use Invoke-Command
with powershell remoting unless this flag is specified. Certain tools that can invoke PowerShell, Ansible for example do
not permit double-hop authentication unless CredSSP authentication is used. For security purposes Kerberos is recommend
over CredSSP, however this does not support double-hop authentication, in which case this flag should be specified.
.PARAMETER ApplyDataMasks
Specifying this optional masks will cause data masks to be applied , as per the dynamic data masking feature first
introduced with SQL Server 2016, this results in this function invoking the Enable-DataMasks function to be invoked. For
documentation on Enable-DataMasks, use the command Get-Help Enable-DataMasks [-Detailed].
.PARAMETER ForceDestDbOffline
Specifying this switch will cause refresh target databases for be forced offline via WITH ROLLBACK IMMEDIATE.
.PARAMETER StaticDataMaskFile
If this parameter is present and has a file path associated with it, the data masking available in version 0.9.725 of the
dbatools module onwards will be applied to the refreshed database. The use of this is contigent on the data mask file
being created and populated in the first place as per this blog post: https://dbatools.io/mask/ .
.EXAMPLE
Invoke-PfaDbRefresh -RefreshDatabase tpch-no-compression `
-RefreshSource z-sql2016-devops-prd `
-DestSqlInstance z-sql2016-devops-tst `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-PromptForSnapshot
Refresh a single database from a snapshot selected from a list of snapshots associated with the volume specified by the RefreshSource parameter.
.EXAMPLE
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -RefreshDatabase tpch-no-compression `
-RefreshSource z-sql2016-devops-prd `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-PromptForSnapshot
Refresh multiple databases from a snapshot selected from a list of snapshots associated with the volume specified by the RefreshSource parameter.
.EXAMPLE
Invoke-PfaDbRefresh -RefreshDatabase tpch-no-compression `
-RefreshSource source-snap `
-DestSqlInstance z-sql2016-devops-tst `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-RefreshFromSnapshot
Refresh a single database using the snapshot specified by the RefreshSource parameter.
.EXAMPLE
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -RefreshDatabase tpch-no-compression `
-RefreshSource source-snap `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-RefreshFromSnapshot
Refresh multiple databases using the snapshot specified by the RefreshSource parameter.
.EXAMPLE
Invoke-PfaDbRefresh -$RefreshDatabase tpch-no-compression `
-RefreshSource z-sql-prd `
-DestSqlInstance z-sql2016-devops-tst `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds
Refresh a single database from the database specified by the SourceDatabase parameter residing on the instance specified by RefreshSource.
.EXAMPLE
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -$RefreshDatabase tpch-no-compression `
-RefreshSource z-sql-prd `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds
Refresh multiple databases from the database specified by the SourceDatabase parameter residing on the instance specified by RefreshSource.
.EXAMPLE
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -$RefreshDatabase tpch-no-compression `
-RefreshSource z-sql-prd `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-ApplyDataMasks
Refresh multiple databases from the database specified by the SourceDatabase parameter residing on the instance specified by RefreshSource.
.EXAMPLE
$StaticDataMaskFile = "D:\apps\datamasks\z-sql-prd.tpch-no-compression.tables.json"
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -$RefreshDatabase tpch-no-compression `
-RefreshSource z-sql-prd `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-StaticDataMaskFile $StaticDataMaskFile
Refresh multiple databases from the database specified by the SourceDatabase parameter residing on the instance specified by RefreshSource and apply SQL Server dynamic data masking to each database.
.EXAMPLE
$StaticDataMaskFile = "D:\apps\datamasks\z-sql-prd.tpch-no-compression.tables.json"
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -$RefreshDatabase tpch-no-compression `
-RefreshSource z-sql-prd `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds `
-ForceDestDbOffline `
-StaticDataMaskFile $StaticDataMaskFile
Refresh multiple databases from the database specified by the SourceDatabase parameter residing on the instance specified by RefreshSource and apply SQL Server dynamic data masking to each database.
All databases to be refreshed are forced offline prior to their underlying FlashArray volumes being overwritten.
.EXAMPLE
$StaticDataMaskFile = "D:\apps\datamasks\z-sql-prd.tpch-no-compression.tables.json"
$Targets = @("z-sql2016-devops-tst", "z-sql2016-devops-dev")
Invoke-PfaDbRefresh -$RefreshDatabase tpch-no-compression `
-RefreshSource z-sql-prd `
-DestSqlInstance $Targets `
-PfaEndpoint 10.225.112.10 `
-PfaCredentials $Creds
-PollJobInterval 10 `
-ForceDestDbOffline `
-StaticDataMaskFile $StaticDataMaskFile
Refresh multiple databases from the database specified by the SourceDatabase parameter residing on the instance specified by RefreshSource and apply SQL Server dynamic data masking to each database.
All databases to be refreshed are forced offline prior to their underlying FlashArray volumes being overwritten. Poll the status of the refresh jobs once every 10 seconds.
.NOTES
Known Restrictions
------------------
1. This function does not currently work for databases associated with
failover cluster instances.
2. This function cannot be used to seed secondary replicas in availability
groups using databases in the primary replica.
3. The function assumes that all database files and the transaction log
reside on a single FlashArray volume.
Obtaining The PureStorageDbaTools Module
----------------------------------------
This function is part of the PureStorageDbaTools module, it is recommend
that the module is always obtained from the PowerShell gallery:
https://www.powershellgallery.com/packages/PureStorageDbaTools
Note that it has dependencies on the dbatools and PureStoragePowerShellSDK
modules which are installed as part of the installation of this module.
Licence
-------
This function is available under the Apache 2.0 license, stipulated as follows:
Copyright 2017 Pure Storage, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.LINK
https://www.powershellgallery.com/packages/PureStorageDbaTools
https://www.purepowershellguy.com/?p=8431
https://dbatools.io/mask/
New-PfaDbSnapshot
Enable-DataMasks
#>
param(
[parameter(mandatory=$true)] [string] $RefreshDatabase
,[parameter(mandatory=$true)] [string] $RefreshSource
,[parameter(mandatory=$true)] [string[]] $DestSqlInstances
,[parameter(mandatory=$true)] [string] $PfaEndpoint
,[parameter(mandatory=$true)] [System.Management.Automation.PSCredential] $PfaCredentials
,[parameter(mandatory=$false)] [int] $PollJobInterval
,[parameter(mandatory=$false)] [switch] $PromptForSnapshot
,[parameter(mandatory=$false)] [switch] $RefreshFromSnapshot
,[parameter(mandatory=$false)] [switch] $NoPsRemoting
,[parameter(mandatory=$false)] [switch] $ApplyDataMasks
,[parameter(mandatory=$false)] [switch] $ForceDestDbOffline
,[parameter(mandatory=$false)] [string] $StaticDataMaskFile
)
$StartMs = Get-Date
if ( $PromptForSnapshot.IsPresent.Equals($false) -And $RefreshFromSnapshot.IsPresent.Equals($false) ) {
try {
$SourceDb = Get-DbaDatabase -sqlinstance $RefreshSource -Database $RefreshDatabase
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to connect to source database $RefreshSource.$Database with: $ExceptionMessage"
Return
}
Write-Color -Text "Source SQL Server instance: ", $RefreshSource, " - CONNECTED" -Color Yellow, Green, Green
try {
$SourceServer = (Connect-DbaInstance -SqlInstance $RefreshSource).ComputerNamePhysicalNetBIOS
}
catch {
Write-Error "Failed to determine target server name with: $ExceptionMessage"
}
}
try {
$FlashArray = New-PfaArray -EndPoint $PfaEndpoint -Credentials $PfaCredentials -IgnoreCertificateError
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to connect to FlashArray endpoint $PfaEndpoint with: $ExceptionMessage"
Return
}
Write-Color -Text "FlashArray endpoint : ", "CONNECTED" -ForegroundColor Yellow, Green
$GetDbDisk = { param ( $Db )
$DbDisk = Get-partition -DriveLetter $Db.PrimaryFilePath.Split(':')[0]| Get-Disk
return $DbDisk
}
$Snapshots = $(Get-PfaAllVolumeSnapshots $FlashArray)
$FilteredSnapshots = $Snapshots.where({ ([string]$_.Source) -eq $RefreshSource })
if ( $PromptForSnapshot.IsPresent ) {
Write-Host ' '
for ($i=0; $i -lt $FilteredSnapshots.Count; $i++) {
Write-Host 'Snapshot ' $i.ToString()
$FilteredSnapshots[$i]
}
$SnapshotId = Read-Host -Prompt 'Enter the number of the snapshot to be used for the database refresh'
}
elseif ( $RefreshFromSnapshot.IsPresent.Equals( $false ) ) {
try {
if ( $NoPsRemoting.IsPresent ) {
$SourceDisk = Invoke-Command -ScriptBlock $GetDbDisk -ArgumentList $SourceDb
}
else {
$SourceDisk = Invoke-Command -ComputerName $SourceServer -ScriptBlock $GetDbDisk -ArgumentList $SourceDb
}
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to determine source disk with: $ExceptionMessage"
Return
}
try {
$SourceVolume = Get-PfaVolumes -Array $FlashArray | Where-Object { $_.serial -eq $SourceDisk.SerialNumber } | Select-Object name
}
catch {
$ExceptionMessage = $_.Exception.Message
Write-Error "Failed to determine source volume with: $ExceptionMessage"
Return
}
}
if ( $PromptForSnapshot.IsPresent ) {
Foreach($DestSqlInstance in $DestSqlInstances) {
Invoke-DbRefresh -DestSqlInstance $DestSqlInstance `
-RefreshDatabase $RefreshDatabase `
-PfaEndpoint $PfaEndpoint `
-PfaCredentials $PfaCredentials `
-SourceVolume $FilteredSnapshots[$SnapshotId]
}
}
else {
$JobNumber = 1
Foreach($DestSqlInstance in $DestSqlInstances) {
$JobName = "DbRefresh" + $JobNumber
Write-Colour -Text "Refresh background job : ", $JobName, " - ", "PROCESSING" -Color Yellow, Green, Green, Green
If ( $RefreshFromSnapshot.IsPresent ) {
Start-Job -Name $JobName -ScriptBlock $Function:DbRefresh -argumentlist $DestSqlInstance , `
$RefreshDatabase , `
$PfaEndpoint , `
$PfaCredentials , `
$RefreshSource , `
$StaticDataMaskFile, `
$ForceDestDbOffline.IsPresent, `
$NoPsRemoting.IsPresent , `
$PromptForSnapshot.IsPresent , `
$ApplyDataMasks.IsPresent | Out-Null
}
else {
Start-Job -Name $JobName -ScriptBlock $Function:DbRefresh -argumentlist $DestSqlInstance , `
$RefreshDatabase , `
$PfaEndpoint , `
$PfaCredentials , `
$SourceVolume.Name , `
$StaticDataMaskFile, `
$ForceDestDbOffline.IsPresent, `
$NoPsRemoting.IsPresent , `
$PromptForSnapshot.IsPresent , `
$ApplyDataMasks.IsPresent | Out-Null
}
$JobNumber += 1;
}
While (Get-Job -State Running | Where-Object {$_.Name.Contains("DbRefresh")}) {
if ($PSBoundParameters.ContainsKey('PollJobInterval')) {
Get-Job -State Running | Where-Object {$_.Name.Contains("DbRefresh")} | Receive-Job
Start-Sleep -Seconds $PollJobInterval
}
else {
Start-Sleep -Seconds 1
}
}
Write-Colour -Text "Refresh background jobs : ", "COMPLETED" -Color Yellow, Green
foreach($job in (Get-Job | Where-Object {$_.Name.Contains("DbRefresh")})) {
$result = Receive-Job $job
Write-Host $result
}
Remove-Job -State Completed
}
$EndMs = Get-Date
Write-Host " "
Write-Host "-------------------------------------------------------" -ForegroundColor Green
Write-Host " "
Write-Host "D A T A B A S E R E F R E S H C O M P L E T E" -ForegroundColor Green
Write-Host " "
Write-Host " Duration (s) = " ($EndMs - $StartMs).TotalSeconds -ForegroundColor White
Write-Host " "
Write-Host "-------------------------------------------------------" -ForegroundColor Green
}
function Enable-DataMasks
{
param(
[parameter(mandatory=$true)] [string] $SqlInstance
,[parameter(mandatory=$true)] [string] $Database
)
Write-Warning "Enable-DataMasks has been deprecated, use Invoke-DynamicDataMasking instead"
}
function Invoke-DynamicDataMasking
{
<#
.SYNOPSIS
A PowerShell function to apply data masks to database columns using the SQL Server dynamic data masking feature.
.DESCRIPTION
This function uses the information stored in the extended properties of a database:
sys.extended_properties.name = 'DATAMASK' to obtain the dynamic data masking function to apply
at column level. Columns of the following data type are currently supported:
- int
- bigint
- char
- nchar
- varchar
- nvarchar
Using the c_address column in the tpch customer table as an example, the DATAMASK extended property can be applied
to the column as follows:
exec sp_addextendedproperty
@name = N'DATAMASK'
,@value = N'(FUNCTION = 'partial(0, "XX", 20)''
,@level0type = N'Schema', @level0name = 'dbo'
,@level1type = N'Table', @level1name = 'customer'
,@level2type = N'Column', @level2name = 'c_address'
GO
.PARAMETER SqlInstance
The SQL Server instance of the database that data masking is to be applied to
.PARAMETER Database
The database that data masking is to be applied to
.EXAMPLE
Invoke-DynamicDataMasking -SqlInstance Z-STN-WIN2016-A\DEVOPSDEV `
-Database tpch-no-compression
.NOTES
Obtaining The PureStorageDbaTools Module
----------------------------------------
This function is part of the PureStorageDbaTools module, it is recommend
that the module is always obtained from the PowerShell gallery:
https://www.powershellgallery.com/packages/PureStorageDbaTools
Note that it has dependencies on the dbatools and PureStoragePowerShellSDK
modules which are installed as part of the installation of this module.
Licence
-------
This function is available under the Apache 2.0 license, stipulated as follows:
Copyright 2017 Pure Storage, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.LINK
https://www.powershellgallery.com/packages/PureStorageDbaTools
https://docs.microsoft.com/en-us/sql/relational-databases/security/dynamic-data-masking?view=sql-server-2017
New-PfaDbSnapshot
Invoke-PfaDbRefresh
#>
param(
[parameter(mandatory=$true)] [string] $SqlInstance
,[parameter(mandatory=$true)] [string] $Database
)
$sql = @"
BEGIN
DECLARE @sql_statement nvarchar(1024)
,@error_message varchar(1024)
DECLARE apply_data_masks CURSOR FOR
SELECT 'ALTER TABLE ' + tb.name + ' ALTER COLUMN ' + c.name +
+ ' ADD MASKED WITH '
+ CAST(p.value AS char) + ''')'
FROM sys.columns c
JOIN sys.types t
ON c.user_type_id = t.user_type_id
LEFT JOIN sys.index_columns ic
ON ic.object_id = c.object_id
AND ic.column_id = c.column_id
LEFT JOIN sys.indexes i
ON ic.object_id = i.object_id
AND ic.index_id = i.index_id
JOIN sys.tables tb
ON tb.object_id = c.object_id
JOIN sys.extended_properties AS p
ON p.major_id = tb.object_id
AND p.minor_id = c.column_id
AND p.class = 1
WHERE t.name IN ('int', 'bigint', 'char', 'nchar', 'varchar', 'nvarchar');
OPEN apply_data_masks
FETCH NEXT FROM apply_data_masks INTO @sql_statement;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Applying data mask: ' + @sql_statement;
BEGIN TRY
EXEC sp_executesql @stmt = @sql_statement
END TRY
BEGIN CATCH
SELECT @error_message = ERROR_MESSAGE();
PRINT 'Application of data mask failed with: ' + @error_message;
END CATCH;
FETCH NEXT FROM apply_data_masks INTO @sql_statement
END;
CLOSE apply_data_masks
DEALLOCATE apply_data_masks;
END;
"@
Invoke-DbaSqlQuery -SqlInstance $SqlInstance -Database $Database -Query $sql
}
function Invoke-StaticDataMasking
{
<#
.SYNOPSIS
A PowerShell function to statically mask data in char, varchar and/or nvarchar columns using a MD5 hashing function.
.DESCRIPTION
This PowerShell function uses as input a JSON file created by calling the New-DbaDbMaskingConfig PowerShell function.
Data in the columns specified in this file which are of the type char, varchar or nvarchar are envrypted using a MD5
hash.
.PARAMETER SqlInstance
The SQL Server instance of the database that static data masking is to be applied to
.PARAMETER Database
The database that static data masking is to be applied to
.PARAMETER DataMaskFile
Absolute path to the JSON file generated by invoking New-DbaDbMaskingConfig. The file can be subsequently editted by
hand to suit the data masking requirements of this function's user. Currently, static data masking is only
supported for columns with char, varchar, nvarchar, int and bigint data types.
.EXAMPLE
Invoke-StaticDataMasking -SqlInstance Z-STN-WIN2016-A\DEVOPSDEV `
-Database tpch-no-compression `
-DataMaskFile 'C:\Users\devops\Documents\tpch-no-compression.tables.json'
.NOTES
Obtaining The PureStorageDbaTools Module
----------------------------------------
This function is part of the PureStorageDbaTools module, it is recommend
that the module is always obtained from the PowerShell gallery:
https://www.powershellgallery.com/packages/PureStorageDbaTools
Note that it has dependencies on the dbatools and PureStoragePowerShellSDK
modules which are installed as part of the installation of this module.
Licence
-------
This function is available under the Apache 2.0 license, stipulated as follows:
Copyright 2017 Pure Storage, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
.LINK
https://www.powershellgallery.com/packages/PureStorageDbaTools
https://docs.microsoft.com/en-us/sql/relational-databases/security/dynamic-data-masking?view=sql-server-2017
New-PfaDbSnapshot
Invoke-PfaDbRefresh
#>
param(
[parameter(mandatory=$true)] [string] $SqlInstance
,[parameter(mandatory=$true)] [string] $Database
,[parameter(mandatory=$true)] [string] $DataMaskFile
)
if ($DataMaskFile.ToString().StartsWith('http')) {
$tables = Invoke-RestMethod -Uri $DataMaskFile
} else {
# Check if the destination is accessible
if (-not (Test-Path -Path $DataMaskFile)) {
Write-Error "Could not find data mask config file $DataMaskFile"
Return
}
}
# Get all the items that should be processed
try {
$tables = Get-Content -Path $DataMaskFile -ErrorAction Stop | ConvertFrom-Json -ErrorAction Stop
} catch {
Write-Error "Could not parse masking config file: $DataMaskFile" -ErrorRecord $_
}
foreach ($tabletest in $tables.Tables) {
if ($Table -and $tabletest.Name -notin $Table) {
continue
}
$ColumnIndex = 0
$UpdateStatement = ""
foreach ($columntest in $tabletest.Columns) {
if ($columntest.ColumnType -in 'varchar', 'char', 'nvarchar') {
if ($ColumnIndex -eq 0) {
$UpdateStatement = 'UPDATE ' + $tabletest.Name + ' SET ' + $columntest.Name + ' = SUBSTRING(CONVERT(VARCHAR, HASHBYTES(' + '''' + 'MD5' + '''' + ', ' + $columntest.Name + '), 1), 1, ' + $columntest.MaxValue + ')'
}
else {
$UpdateStatement += ', ' + $columntest.Name + ' = SUBSTRING(CONVERT(VARCHAR, HASHBYTES(' + '''' + 'MD5' + '''' + ', ' + $columntest.Name + '), 1), 1, ' + $columntest.MaxValue + ')'
}
}
elseif ($columntest.ColumnType -eq 'int') {
if ($ColumnIndex -eq 0) {
$UpdateStatement = 'UPDATE ' + $tabletest.Name + ' SET ' + $columntest.Name + ' = ABS(CHECKSUM(NEWID())) % 2147483647'