-
Notifications
You must be signed in to change notification settings - Fork 17
/
PSBlitz.ps1
7074 lines (6553 loc) · 284 KB
/
PSBlitz.ps1
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
<#
.SYNOPSIS
Outputs SQL Server health and performance diagnostics data to either Excel or HTML,
and saves execution plans and deadlock graphs as .sqlplan and .xdl files.
.DESCRIPTION
Outputs the following to an Excel spreadsheet or to an HTML report:
Instance information
Wait stats - from sp_BlitzFirst
Currently opened transactions (if any)
Currently running queries - from sp_BlitzWho
Instance health-related findings - from sp_Blitz
tempdb size and usage information per object and session
Index-related issues and recommendations - from sp_BlitzIndex
Top 10 most resource intensive queries - from sp_BlitzCache
Deadlock related information from the past 15 days - from sp_BlitzLock
Information about all databases and their files or for a single database in
case of a database-specific check
Query Store information in the case of a database-specific check on an eligible database - from
sp_BlitzQueryStore
Statistics details for a given database - in the case of database-specific check or if a database
accounts for at least 2/3 of the sp_BlitzCache data
Index Fragmentation information for a given database - in the case of database-specific check or if
a database accounts for at least 2/3 of the sp_BlitzCache data
Note: If the execution of PSBlitz took longer than 15 minutes up until the call to sp_BlitzLock, the timeframe for
sp_BlitzLock will be narrowed down to the last 7 days in order to keep execution time within a reasonable amount.
Exports the following files:
Execution plans (as .sqlplan files) - from the same dataset generated by sp_BlitzCache
Execution plans (as .sqlplan files) - from the sample execution plans provided by sp_BlitzIndex @Mode = 0
and sp_BlitzIndex @Mode = 4 for missing index suggestions (only on SQL Server 2019)
Execution plans (as .sqlplan files) of currently running sessions - from the same dataset generated by sp_BlitzWho
Deadlock graphs (as .xdl files) - from the same dataset generated by sp_BlitzLock
Execution plans (as .sqlplan files) - from sp_BlitzLock if any of the execution plans involved in deadlocks are still
in the plan cache at the time of the check
Execution plans (as .sqlplan files) - from sp_BlitzQueryStore in the case of a database-specific check
on an eligible database
PSBlitz.ps1 uses slightly modified, non-stored procedure versions, of the following components from Brent Ozar's
SQL Server First Responder Kit:
sp_Blitz
sp_BlitzCache
sp_BlitzFirst
sp_BlitzIndex
sp_BlitzLock
sp_BlitzWho
sp_BlitzQueryStore
Aside from the above scripts, PSBlitz also runs the following scripts to return sp_BlitzWho data, instance and resource
information, index fragmentation and stats info, database and database files info, as well as TempDB usage:
GetDbInfo.sql
GetBlitzWhoData.sql
GetInstanceInfo.sql
GetAzureSQLDBInfo.sql
GetTempDBUsageInfo.sql
GetStatsInfoForWholeDB.sql
GetIndexInfoForWholeDB.sql
Prerequisites
If you want the report to be in Excel format, then the MS Office suite needs to be installed on the machine where
you're executing PSBlitz, otherwise use the HTML format.
PSBlitz will auto-default to HTML output on when ran on a host that does not have the MS Office suite installed.
Sufficient permissions to query DMVs, server state, and get database objects' definitions.
You don't need to have any of the sp_Blitz stored procedures present on the instance that you're executing PSBlitz.ps1 for,
all the scripts are contained in the PSBlitz\Resources directory in non-stored procedure format.
Eecution
You can run PSBlitz.ps1 by simply right-clicking on the script and then clicking on "Run With PowerShell" which will execute
the script in interactive mode, prompting you for the required input.
Otherwise you can navigate to the directory where the script is in PowerShell and execute it by providing parameters
and appropriate values.
License
MIT License
Copyright for sp_Blitz, sp_BlitzCache, sp_BlitzFirst, sp_BlitzIndex,
sp_BlitzLock, and sp_BlitzWho is held by Brent Ozar Unlimited under MIT licence:
SQL Server First Responder Kit - https://github.com/BrentOzarULTD/SQL-Server-First-Responder-Kit
Copyright for PSBlitz.ps1, GetStatsInfoForWholeDB.sql, GetOpenTransactions.sql,
GetIndexInfoForWholeDB.sql, GetInstanceInfo.sql, and GetTempDBUsageInfo.sql
is held by Vlad Drumea, 2024 as described below.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
.PARAMETER ServerName
Accepts either HostName\InstanceID (for named instances), HostName,Port when using a port number instead of an instance ID,
or just HostName for default instances. If you provide either ? or Help as a value for -ServerName,
the script will return a brief help menu.
.PARAMETER SQLLogin
The name of the SQL login used to run the script. If not provided, the script will use integrated security.
.PARAMETER SQLPass
The password for the SQL login provided via the -SQLLogin parameter, omit if -SQLLogin was not used.
.PARAMETER IsIndepth
Providing Y as a value will tell PSBlitz.ps1 to run a more in-depth check against the instance/database.
Omit for default check.
.PARAMETER CheckDB
Used to provide the name of a specific database against which sp_BlitzIndex, sp_BlitzCache,
and sp_BlitzLock will be ran. Omit to run against the whole instance.
Also used to provide the name of the Azure SQL DB database.
.PARAMETER CacheTop
Used to specify if more/less than the default top 10 queries should be returned for the
sp_BlitzCache step. Only works for HTML output (-ToHTM Y).
.PARAMETER CacheMinutesBack
Used to specify how many minutes back to begin plan cache analysis.
Defaults to entire contents of the plan cache since instance startup.
In order to avoid missing the desired timeframe, the value is dynamically adjusted based on
the runtime of PSBlitz up until the plan cache analysis point.
.PARAMETER OutputDir
Used to provide a path where the output directory should be saved to. Defaults to PSBlitz.ps1's directory
if not specified or a non-existent path is provided.
.PARAMETER ToHTML
Providing Y as a value will tell PSBlitz.ps1 to output the report as HTML instead of an Excel file.
This is perfect when running PSBlitz from a machine that doesn't have Office installed.
.PARAMETER ZipOutput
Providing Y as a value will tell PSBlitz.ps1 to also create a zip archive of the output files.
.PARAMETER BlitzWhoDelay
Used to sepcify the number of seconds between each sp_BlitzWho execution. Defaults to 10 if not specified.
.PARAMETER ConnTimeout
Can be used to increased the timeout limit in seconds for connecting to SQL Server. Defaults to 15 seconds if not specified.
.PARAMETER MaxTimeout
Can be used to set a higher timeout for sp_BlitzIndex and Stats and Index info retrieval. Defaults to 1000 (16.6 minutes)
.PARAMETER MaxUsrDBs
Can be used to tell PSBlitz to raise the limit of user databases based on which index-related info is
limited to only the "loudest" database in the cache results. Defaults to 50 - only change it if you're using using HTML output
and have enough RAM to handle the increased data that PS will have to process.
.PARAMETER DebugInfo
Switch used to get more information for debugging and troubleshooting purposes.
.NOTES
Author: Vlad Drumea (VladDBA)
Website: https://vladdba.com/
Copyright: (c) 2024 by Vlad Drumea, licensed under MIT
License: MIT https://opensource.org/licenses/MIT
.LINK
https://github.com/VladDBA/PSBlitz
.EXAMPLE
PS>.\PSBlitz.ps1 ?
PS>.\PSBlitz.ps1 Help
Print the help menu
.EXAMPLE
PS>.\PSBlitz.ps1 Server01\SQL01
Run it against the whole instance (named instance SQL01), with default checks via integrated security
.EXAMPLE
PS>.\PSBlitz.ps1 Server01,1433
Run it against the whole instance listening on port 1433 on host Server01, with default checks via integrated security
.EXAMPLE
PS>.\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y
Run it against the whole instance, with in-depth checks via integrated security
.EXAMPLE
PS>.\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y -CheckDB YourDatabase
Run it with in-depth checks, limit sp_BlitzIndex, sp_BlitzCache, and sp_BlitzLock to YourDatabase only, via integrated security
.EXAMPLE
PS>.\PSBlitz.ps1 Server01\SQL01 -SQLLogin DBA1 -SQLPass SuperSecurePassword
Run it against the whole instance, with default checks via SQL login and password
.EXAMPLE
PS>.\PSBlitz.ps1 yourserver.database.windows.net,1433:YourDatabase -SQLLogin DBA1 -SQLPass SuperSecurePassword
Run it against the YourDatabase database hosted in Azure SQL DB at myserver.database.windows.net port 1433 via SQL login and password
.EXAMPLE
PS>.\PSBlitz.ps1 Server02 -SQLLogin DBA1 -SQLPass SuperSecurePassword -IsIndepth Y -CheckDB YourDatabase
Run it against a default instance residing on Server02, with in-depth checks via SQL login and password,
while limmiting sp_BlitzIndex, sp_BlitzCache, and sp_BlitzLock to YourDatabase only
.EXAMPLE
PS>.\PSBlitz.ps1 Server02 -SQLLogin DBA1 -SQLPass SuperSecurePassword -IsIndepth Y -CheckDB YourDatabase -MaxTimeout 1200 -BlitzWhoDelay 20 -DebugInfo -OutputDir C:\Temp
Run the same command as above, but increase execution timeout for sp_BlitzIndex, stats and index info retrieval,
while also increasing delay between sp_BlitzWHo executions as well as getting more verbose console output
and saving the output directory to C:\temp
.EXAMPLE
PS>.\PSBlitz.ps1 Server01\SQL01 -ToHTML Y -ZipOutput Y
Run PSBlitz but output the report as HTML instead of XLSX while also creating a zip archive of the output files.
.EXAMPLE
PS>.\PSBlitz.ps1 yourserver.database.windows.net,1433:YourDatabase -SQLLogin DBA1 -SQLPass SuperSecurePassword
Run it against the YourDatabase database hosted in Azure SQL DB at yourserver.database.windows.net port 1433 via SQL login and password
.EXAMPLE
PS>.\PSBlitz.ps1 yourserver.database.windows.net -SQLLogin DBA1 -SQLPass SuperSecurePassword
Run it against the Azure SQL Managed Instance yourserver.database.windows.net
.EXAMPLE
PS>.\PSBlitz.ps1 yourserver.database.windows.net -SQLLogin DBA1 -SQLPass SuperSecurePassword -IsIndepth Y -CheckDB YourDatabase
Run it against the Azure SQL Managed Instance yourserver.database.windows.net with an in-depth check while limiting index, stats, plan cache, and database info to YourDatabase
#>
###Input Params
##Params for running from command line
[cmdletbinding()]
param(
[Parameter(Position = 0, Mandatory = $False)]
[string[]]$ServerName,
[Parameter(Mandatory = $False)]
[string]$SQLLogin,
[Parameter(Mandatory = $False)]
[string]$SQLPass,
[Parameter(Mandatory = $False)]
[string]$IsIndepth,
[Parameter(Mandatory = $False)]
[string]$CheckDB,
[Parameter(Mandatory = $False)]
[string]$Help,
[Parameter(Mandatory = $False)]
[int]$BlitzWhoDelay = 10,
[Parameter(Mandatory = $False)]
[switch]$DebugInfo,
[Parameter(Mandatory = $False)]
[int]$MaxTimeout = 1000,
[Parameter(Mandatory = $False)]
[int]$ConnTimeout = 15,
[Parameter(Mandatory = $False)]
[string]$OutputDir,
[Parameter(Mandatory = $False)]
[string]$ToHTML = "N",
[Parameter(Mandatory = $False)]
[string]$ZipOutput = "N",
[Parameter(Mandatory = $False)]
[int]$CacheTop = 10,
[Parameter(Mandatory = $False)]
[int]$CacheMinutesBack = 0,
[Parameter(Mandatory = $False)]
[int]$MaxUsrDBs = 50
)
###Internal params
#Version
$Vers = "4.5.0"
$VersDate = "2024-11-20"
$TwoMonthsFromRelease = [datetime]::ParseExact("$VersDate", 'yyyy-MM-dd', $null).AddMonths(2)
$NowDate = Get-Date
#Get script path
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
#clear previous errors
$error.Clear();
#Set resources path
$ResourcesPath = Join-Path -Path $ScriptPath -ChildPath "Resources"
#Set name of the input Excel file
$OrigExcelFName = "PSBlitzOutput.xlsx"
$ResourceList = @("PSBlitzOutput.xlsx", "spBlitz_NonSPLatest.sql",
"spBlitzCache_NonSPLatest.sql", "spBlitzFirst_NonSPLatest.sql",
"spBlitzIndex_NonSPLatest.sql", "spBlitzLock_NonSPLatest.sql",
"spBlitzWho_NonSPLatest.sql",
"GetBlitzWhoData.sql", "GetInstanceInfo.sql",
"GetTempDBUsageInfo.sql", "GetOpenTransactions.sql",
"GetStatsInfoForWholeDB.sql", "GetIndexInfoForWholeDB.sql",
"GetDbInfo.sql", "GetAzureSQLDBInfo.sql",
"spBlitzQueryStore_NonSPLatest.sql", "searchtable.js", "sorttable.js",
"styles.css")
#Set path+name of the input Excel file
$OrigExcelF = Join-Path -Path $ResourcesPath -ChildPath $OrigExcelFName
#Set default start row for Excel output
$DefaultStartRow = 2
#BlitzWho initial pass number
$BlitzWhoPass = 1
if ($DebugInfo) {
#Success
$GreenCheck = @{
Object = [Char]8730
ForegroundColor = 'Green'
NoNewLine = $true
}
#Failure
$RedX = @{
Object = 'x (Failed)'
ForegroundColor = 'Red'
NoNewLine = $true
}
#Command Timeout
$RedXTimeout = @{
Object = 'x (Command timeout)'
ForegroundColor = 'Red'
NoNewLine = $true
}
#Connection Timeout
$RedXConnTimeout = @{
Object = 'x (Connection timeout)'
ForegroundColor = 'Red'
NoNewLine = $true
}
}
else {
#Success
$GreenCheck = @{
Object = [Char]8730
ForegroundColor = 'Green'
NoNewLine = $false
}
#Failure
$RedX = @{
Object = 'x (Failed)'
ForegroundColor = 'Red'
NoNewLine = $false
}
#Command Timeout
$RedXTimeout = @{
Object = 'x (Command timeout)'
ForegroundColor = 'Red'
NoNewLine = $false
}
#Connection Timeout
$RedXConnTimeout = @{
Object = 'x (Connection timeout)'
ForegroundColor = 'Red'
NoNewLine = $false
}
}
###Functions
#Function to properly output hex strings like Plan Handle and SQL Handle
function Get-HexString {
param (
[System.Array]$HexInput
)
if ($HexInput -eq [System.DBNull]::Value) {
$HexString = ""
}
else {
#Formatting value as hex and stripping extra stuff
$HexSplit = ($HexInput | Format-Hex -ErrorAction Ignore | Select-String "00000")
<#
Converting to string, prepending 0x, removing spaces
and joining it in one single string
#>
$HexString = "0x"
for ($i = 0; $i -lt $HexSplit.Length; $i++) {
$HexString = $HexString + "$($HexSplit[$i].ToString().Substring(11,47).replace(' ','') )"
}
}
Write-Output $HexString
}
#Function to return a brief help menu
function Get-PSBlitzHelp {
Write-Host "`n###### PSBlitz ######`n Version $Vers - $VersDate
`n Updates/more info: https://github.com/VladDBA/PSBlitz
`n###### Parameters ######
-ServerName - accepts either [hostname]\[instance] (for named instances),
[hostname,port], or just [hostname] for default instances
-SQLLogin - the name of the SQL login used to run the script; if not provided,
the script will use integrated security
-SQLPass - the password for the SQL login provided via the -SQLLogin parameter,
omit if -SQLLogin was not used
-IsIndepth - Y will run a more in-depth check against the instance/database, omit for a basic check
-CheckDB - used to provide the name of a specific database to run some of the checks against,
omit to run against the whole instance
-OutputDir - used to provide a path where the output directory should be saved to.
Defaults to PSBlitz.ps1's directory if not specified or a non-existent path is provided.
-ToHTML - Y will output the report as HTML instead of an Excel file.
-ZipOutput - Y to also create a zip archive of the output files.
-BlitzWhoDelay - used to sepcify the number of seconds between each sp_BlitzWho execution.
Defaults to 10 if not specified
-CacheTop - used to specify if more/less than the default top 10 queries should be returned
for the sp_BlitzCache step. Only works for HTML output (-ToHTM Y).
-CacheMinutesBack - used to specify how many minutes back to begin plan cache analysis.
Defaults to entire contents of the plan cache since instance startup.
In order to avoid missing the desired timeframe, the value is dynamically adjusted based on
the runtime of PSBlitz up until the plan cache analysis point.
-MaxTimeout - can be used to set a higher timeout for sp_BlitzIndex and Stats and Index info
retrieval. Defaults to 1000 (16.6 minutes)
-ConnTimeout - used to increased the timeout limit in seconds for connecting to SQL Server.
Defaults to 15 seconds if not specified
-DebugInfo - switch used to get more information for debugging and troubleshooting purposes.
`n###### Execution ######
You can either run the script directly in PowerShell from its directory:
Run it against the whole instance (named instance SQL01), with default checks via integrated security"
Write-Host ".\PSBlitz.ps1 Server01\SQL01" -fore green
Write-Host "`n Same as the above, but have sp_BlitzWho execute every 5 seconds instead of 10"
Write-Host ".\PSBlitz.ps1 Server01\SQL01 -BlitzWhoDelay 5" -fore green
Write-Host "`n Run it against an instance listening on port 1433 on Server01"
Write-Host ".\PSBlitz.ps1 Server01,1433" -fore green
Write-Host "`n Run it against a default instance installed on Server01"
Write-Host ".\PSBlitz.ps1 Server01" -fore green
Write-Host "`n Run it against the whole instance, with in-depth checks via integrated security"
Write-Host ".\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y" -fore green
Write-Host "`n Run it against the whole instance and output the report as HTML"
Write-Host ".\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y -ToHTML Y" -fore green
Write-Host "`n Run it with in-depth checks, limit sp_BlitzIndex, sp_BlitzCache, and sp_BlitzLock to
YourDatabase only, via integrated security"
Write-Host ".\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y -CheckDB YourDatabase" -fore green
Write-Host "`n Run it against the whole instance, with default checks via SQL login and password"
Write-Host ".\PSBlitz.ps1 Server01\SQL01 -SQLLogin DBA1 -SQLPass SuperSecurePassword" -fore green
Write-Host "`n Run it against the YourDatabase database hosted in Azure SQL DB at myserver.database.windows.net port 1433 via SQL login and password"
Write-Host "\PSBlitz.ps1 yourserver.database.windows.net,1433:YourDatabase -SQLLogin DBA1 -SQLPass SuperSecurePassword"
Write-Host "`n Or you can run it in interactive mode by just right-clicking on the PSBlitz.ps1 file
-> 'Run with PowerShell', and the script will prompt you for input.
`n###### What it runs ######
PSBlitz.ps1 uses slightly modified, non-stored procedure versions, of the following components
from Brent Ozar's FirstResponderKit (https://www.brentozar.com/first-aid/):
sp_Blitz
sp_BlitzCache
sp_BlitzFirst
sp_BlitzIndex
sp_BlitzLock
sp_BlitzWho
sp_BlitzQueryStore
`n You can find the scripts in the '$ResourcesPath' directory
"
}
#Function to execute sp_BlitzWho
function Invoke-BlitzWho {
param (
[string]$BlitzWhoQuery,
[string]$IsInLoop
)
if ($IsInLoop -eq "Y") {
Write-Host " ->Active session data capture - pass $BlitzWhoPass... " -NoNewLine
}
else {
Write-Host " Active session data capture - pass $BlitzWhoPass... " -NoNewLine
}
$StepStart = Get-Date
$StepName = "sp_BlitzWho - pass $BlitzWhoPass"
$BlitzWhoCommand = new-object System.Data.SqlClient.SqlCommand
$BlitzWhoCommand.CommandText = $BlitzWhoQuery
$BlitzWhoCommand.CommandTimeout = 120
$SqlConnection.Open()
$BlitzWhoCommand.Connection = $SqlConnection
Try {
$BlitzWhoCommand.ExecuteNonQuery() | Out-Null -ErrorAction Stop
$SqlConnection.Close()
Write-Host @GreenCheck
$StepEnd = Get-Date
Add-LogRow $StepName "Success"
}
Catch {
Write-Host @RedX
$StepEnd = Get-Date
Add-LogRow $StepName "Failure"
}
}
#Function to properly format XML contents for deadlock graphs and execution plans
function Format-XML {
[CmdletBinding()]
Param ([
Parameter(ValueFromPipeline = $true, Mandatory = $true)]
[string]$XMLContent)
$XMLDoc = New-Object -TypeName System.Xml.XmlDocument
$XMLDoc.LoadXml($XMLContent)
$SW = New-Object System.IO.StringWriter
$Writer = New-Object System.Xml.XmlTextwriter($SW)
$Writer.Formatting = [System.XML.Formatting]::Indented
$XMLDoc.WriteContentTo($Writer)
$SW.ToString()
}
#Function to format exception messages
function Format-ExceptionMsg {
$ErrorMessage = $error[0]
[string]$ErrorMessageString = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty Message
try {
[string]$SQLErrNo = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty Number -ErrorAction Ignore
if (!([string]::IsNullOrEmpty($SQLErrNo))) {
#Get SQL related error info
[string]$SQLErrState = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty State -ErrorAction Stop
[string]$SQLErrLev = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty Class
[string]$SQLErrState = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty State
[string]$SQLErrLineNo = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty LineNumber
[string]$SQLErrMsg = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty Message
##formatting the error message in SQL Server style if there's an error number
Write-Output "SQL Error: MSg $SQLErrNo, Level $SQLErrLev, State $SQLErrState, Line $SQLErrLineNo `n $SQLErrMsg"
}
else {
#Get PS related error info
[string]$PSErrMsg = $ErrorMessageString
[string]$PSErrLine = $ErrorMessage | Select-Object -ExpandProperty InvocationInfo | Select-Object -ExpandProperty ScriptLineNumber -ErrorAction Stop
[string]$PSErrStatement = $ErrorMessage | Select-Object -ExpandProperty InvocationInfo | Select-Object -ExpandProperty Line
if (!([string]::IsNullOrEmpty($PSErrStatement))) {
$PSErrStatement = $PSErrStatement.Trim()
}
if (!([string]::IsNullOrEmpty($PSErrMsg))) {
Write-Output "PS Error: Script Line $PSErrLine `n Message $PSErrMsg `n Statement $PSErrStatement"
}
else {
Write-Output "No exceptions encountered."
}
}
}
catch {
Write-Output $ErrorMessageString
}
}
#Function to return error messages in the catch block
function Invoke-ErrMsg {
$StepRunTime = (New-TimeSpan -Start $StepStart -End $StepEnd).TotalSeconds
$RunTime = [Math]::Round($StepRunTime, 2)
if ($RunTime -ge $CmdTimeout) {
Write-Host @RedXTimeout
if ($DebugInfo) {
Write-Host " - $RunTime seconds" -Fore Yellow
}
$OutErr = Format-ExceptionMsg
Write-Host " $OutErr" -fore Red
}
<#elseif ($RunTime -ge $ConnTimeout) {
Write-Host @RedXConnTimeout
if ($DebugInfo) {
Write-Host " - $RunTime seconds" -Fore Yellow
}
}#>
else {
Write-Host @RedX
if ($DebugInfo) {
Write-Host " - $RunTime seconds" -Fore Yellow
}
$OutErr = Format-ExceptionMsg
Write-Host " $OutErr" -fore Red
}
}
function Get-ExecTime {
$StepRunTime = (New-TimeSpan -Start $StepStart -End $StepEnd).TotalSeconds
[string]$StepDUration = [Math]::Round($StepRunTime, 2).ToString()
Write-Output $StepDUration
}
function Add-LogRow {
[CmdletBinding()]
Param ([
Parameter(Position = 0, Mandatory = $true)]
[string]$StepName,
[Parameter(Position = 1, Mandatory = $true)]
[string]$StepStatus,
[Parameter(Position = 2, Mandatory = $false)]
[string]$MoreInfo = ""
)
$ExecTime = Get-ExecTime
$ErrMsg = Format-ExceptionMsg
$LogRow = $LogTbl.NewRow()
$LogRow.Step = $StepName
$LogRow.StartDate = $StepStart.ToString("yyyy-MM-dd HH:mm:ss")
$LogRow.EndDate = $StepEnd.ToString("yyyy-MM-dd HH:mm:ss")
$LogRow.Duration = $ExecTime
$LogRow.Outcome = $StepStatus
if ("Interrupted", "Failure" -contains $StepStatus ) {
$LogRow.ErrorMsg = $ErrMsg
}
elseif ($StepStatus -eq "Success") {
$LogRow.ErrorMsg = $MoreInfo
}
else {
$LogRow.ErrorMsg = $MoreInfo
}
$LogTbl.Rows.Add($LogRow)
}
###Job preparation
#sp_BlitzWho
$InitScriptBlock = {
function Invoke-BlitzWho {
param (
[string]$BlitzWhoQuery
)
$BlitzWhoCommand = new-object System.Data.SqlClient.SqlCommand
$BlitzWhoCommand.CommandText = $BlitzWhoQuery
#increased BlitzWho command timeout from 20 to 60 because some people have been getting errors
#considering setting @ExpertMode = 0 if this keeps up
$BlitzWhoCommand.CommandTimeout = 60
$SqlConnection.Open()
$BlitzWhoCommand.Connection = $SqlConnection
$BlitzWhoCommand.ExecuteNonQuery() | Out-Null
$SqlConnection.Close()
}
function Format-ExceptionMsg {
$ErrorMessage = $error[0]
[string]$ErrorMessageString = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty Message
try {
[string]$SQLErrNo = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty Number -ErrorAction Ignore
if (!([string]::IsNullOrEmpty($SQLErrNo))) {
#Get SQL related error info
[string]$SQLErrState = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty State -ErrorAction Stop
[string]$SQLErrLev = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty Class
[string]$SQLErrLineNo = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty LineNumber
[string]$SQLErrMsg = $ErrorMessage | Select-Object -ExpandProperty Exception | Select-Object -ExpandProperty InnerException | Select-Object -ExpandProperty Message
##formatting the error message in SQL Server style if there's an error number
Write-Output "SQL Error: MSg $SQLErrNo, Level $SQLErrLev, State $SQLErrState, Line $SQLErrLineNo `n $SQLErrMsg"
}
else {
#Get PS related error info
[string]$PSErrMsg = $ErrorMessageString
[string]$PSErrLine = $ErrorMessage | Select-Object -ExpandProperty InvocationInfo | Select-Object -ExpandProperty ScriptLineNumber -ErrorAction Stop
[string]$PSErrStatement = $ErrorMessage | Select-Object -ExpandProperty InvocationInfo | Select-Object -ExpandProperty Line
if (!([string]::IsNullOrEmpty($PSErrStatement))) {
$PSErrStatement = $PSErrStatement.Trim()
}
if (!([string]::IsNullOrEmpty($PSErrMsg))) {
Write-Output "PS Error: Script Line $PSErrLine `n Message $PSErrMsg `n Statement $PSErrStatement"
}
else {
Write-Output "No exceptions encountered."
}
}
}
catch {
Write-Output $ErrorMessageString
}
}
function Invoke-FlagTableCheck {
param (
[string]$FlagTblDt
)
$CheckFlagTblQuery = new-object System.Data.SqlClient.SqlCommand
$FlagTblQuery = "DECLARE @FlagTable NVARCHAR(300); `n SELECT @FlagTable = CASE "
$FlagTblQuery += "WHEN CAST(SERVERPROPERTY('Edition') AS NVARCHAR(128)) = N'SQL Azure' "
$FlagTblQuery += "`nAND SERVERPROPERTY('EngineEdition') IN (5, 6) "
$FlagTblQuery += "`nTHEN N'BlitzWhoOutFlag_$FlagTblDt' ELSE "
$FlagTblQuery += "`nN'tempdb.dbo.BlitzWhoOutFlag_$FlagTblDt' END; "
$FlagTblQuery += "`nSELECT CASE WHEN OBJECT_ID(@FlagTable, N'U') IS NOT NULL "
$FlagTblQuery += "`nTHEN 'Y' ELSE 'N' END AS [FlagFound];"
$CheckFlagTblQuery.CommandText = $FlagTblQuery
$CheckFlagTblQuery.Connection = $SqlConnection
$CheckFlagTblQuery.CommandTimeout = 30
$CheckFlagTblAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$CheckFlagTblAdapter.SelectCommand = $CheckFlagTblQuery
$CheckFlagTblSet = new-object System.Data.DataSet
Try {
$CheckFlagTblAdapter.Fill($CheckFlagTblSet) | Out-Null -ErrorAction Stop
$SqlConnection.Close()
[string]$IsFlagTbl = $CheckFlagTblSet.Tables[0].Rows[0]["FlagFound"]
}
Catch {
[string]$IsFlagTbl = "X"
}
if ($IsFlagTbl -eq "Y") {
$CleanupCommand = new-object System.Data.SqlClient.SqlCommand
$Cleanup = "DECLARE @SQL NVARCHAR(400);`nSELECT @SQL = N'DROP TABLE '+ CASE "
$Cleanup += "`nWHEN CAST(SERVERPROPERTY('Edition') AS NVARCHAR(100)) = N'SQL Azure' "
$Cleanup += "`nAND SERVERPROPERTY('EngineEdition') IN (5, 6) "
$Cleanup += "`nTHEN N'[BlitzWhoOutFlag_$FlagTblDt];' "
$Cleanup += "`nELSE N'[tempdb].[dbo].[BlitzWhoOutFlag_$FlagTblDt];' `nEND; `nEXEC(@SQL);"
$CleanupCommand.CommandText = $Cleanup
$CleanupCommand.CommandTimeout = 20
$SqlConnection.Open()
$CleanupCommand.Connection = $SqlConnection
$CleanupCommand.ExecuteNonQuery() | Out-Null
$SqlConnection.Close()
$SqlConnection.Dispose()
}
return $IsFlagTbl
}
}
$MainScriptblock = {
Param([string]$ConnStringIn , [string]$BlitzWhoIn, [string]$DirDateIn, [int]$BlitzWhoDelayIn)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $ConnStringIn
[int]$SuccessCount = 0
[int]$FailedCount = 0
[int]$FlagCheckRetry = 0
[string]$IsFlagTbl = "N"
[string]$FlagErrCheck = "N"
while (($IsFlagTbl -ne "Y") -and ($FlagCheckRetry -le 3)) {
Try {
Invoke-BlitzWho -BlitzWhoQuery $BlitzWhoIn
$SuccessCount += 1
}
Catch {
$FailedCount += 1
}
[string]$IsFlagTbl = Invoke-FlagTableCheck -FlagTblDt $DirDateIn
#Reset retry count if failures aren't consecutive
if (($FlagErrCheck -eq "X") -and ($IsFlagTbl -ne "X")) {
$FlagCheckRetry = 0
}
if ($IsFlagTbl -eq "N") {
Start-Sleep -Seconds $BlitzWhoDelayIn
}
if ($IsFlagTbl -eq "X") {
$FlagCheckRetry += 1
$FlagErrCheck = $IsFlagTbl
$IsFlagTbl = "N"
}
}
if ($FailedCount -gt 0) {
$OutMsg = " ->Successful runs: $SuccessCount"
#Write-Host " ->Successful runs: $SuccessCount" -NoNewLine
$OutMsg += "; Failed runs: $FailedCount"
#Write-Host "; Failed runs: $FailedCount" -NoNewLine
if ($FlagCheckRetry -gt 0) {
$OutMsg += "; Retries: $FlagCheckRetry"
#Write-Host "; Retries: $FlagCheckRetry"
$OutErr = Format-ExceptionMsg
$OutMsg += "`n $OutErr"
Write-Output $OutMsg
}
else {
$OutMsg += ""
#Write-Host ""
$OutErr = Format-ExceptionMsg
$OutMsg += "`n $OutErr"
Write-Output $OutMsg
#Write-Host " $OutErr" -fore Red
}
$SqlConnection.Dispose()
}
else {
$OutMsg = " ->Successful runs: $SuccessCount"
#Write-Host " ->Successful runs: $SuccessCount" -NoNewLine
if ($FlagCheckRetry -gt 0) {
$OutMsg += "; Consecutive retries: $FlagCheckRetry"
#Write-Host "; Consecutive retries: $FlagCheckRetry"
Write-Output $OutMsg
}
else {
$OutMsg += ""
#Write-Host ""
Write-Output $OutMsg
}
$SqlConnection.Dispose()
}
}
###Convert $ServerName from array to string
[string]$ServerName = $ServerName -join ","
###Return help if requested during execution
if (("Y", "Yes" -Contains $Help) -or ("?", "Help" -Contains $ServerName)) {
Get-PSBlitzHelp
Exit
}
###Validate existence of dependencies
#Check resources path
if (!(Test-Path $ResourcesPath )) {
Write-Host "The Resources directory was not found in $ScriptPath!" -fore red
Write-Host " Make sure to download the latest release from https://github.com/VladDBA/PSBlitz/releases" -fore yellow
Write-Host "and properly extract the contents" -fore yellow
Read-Host -Prompt "Press Enter to close this window."
Exit
}
#Check individual files
$MissingFiles = @()
foreach ($Rsc in $ResourceList) {
$FileToTest = Join-Path -Path $ResourcesPath -ChildPath $Rsc
if (!(Test-Path $FileToTest -PathType Leaf)) {
$MissingFiles += $Rsc
}
}
if ($MissingFiles.Count -gt 0) {
Write-Host "The following files are missing from"$ResourcesPath":" -fore red
foreach ($MIAFl in $MissingFiles) {
Write-Host " $MIAFl" -fore red
}
Write-Host " Make sure to download the latest release from https://github.com/VladDBA/PSBlitz/releases" -fore yellow
Write-Host "and properly extract the contents" -fore yellow
Read-Host -Prompt "Press Enter to close this window."
Exit
}
$IsAzureSQLDB = $false
$IsAzureSQLMI = $false
$IsAzure = $false
###Switch to interactive mode if $ServerName is empty
if ([string]::IsNullOrEmpty($ServerName)) {
Write-Host "Running in interactive mode"
$InteractiveMode = 1
##Instance
while ([string]::IsNullOrEmpty($ServerName)) {
$ServerName = Read-Host -Prompt "Server"
}
#Make ServerName filename friendly and get host name
if ($ServerName -like "*`"*") {
$ServerName = $ServerName -replace "`"", ""
}
if ($ServerName -like "*\*") {
$pos = $ServerName.IndexOf("\")
$InstName = $ServerName.Substring($pos + 1)
$HostName = $ServerName.Substring(0, $pos)
}
#Azure SQL DB
elseif ($ServerName -like "*database.windows.net*") {
$IsAzure = $true
#let's strip "tcp: first just in case"
if ($ServerName -like "tcp:*") {
$TCPStripped = $true
$ServerName = $ServerName -replace "tcp:", ""
}
#get the database name if it was provided
if ($ServerName -like "*:*") {
$pos = $ServerName.IndexOf(":")
[string]$ASDBName = $ServerName.Substring($pos + 1)
$ServerName = $ServerName.Substring(0, $pos)
if (!([string]::IsNullOrEmpty($ASDBName))) {
$IsAzureSQLDB = $true
}
}
#Get the hostname
if ($ServerName -like "*,*") {
$pos = $ServerName.IndexOf(",")
$HostName = $ServerName.Substring(0, $pos)
}
else {
$HostName = $ServerName
}
$InstName = $HostName
#slap tcp: back on because why not
if ($TCPStripped) {
$ServerName = "tcp:$ServerName"
}
}
elseif ($ServerName -like "*,*") {
$pos = $ServerName.IndexOf(",")
$HostName = $ServerName.Substring(0, $pos)
$InstName = $ServerName -replace ",", "-"
if ($HostName -like "tcp:*") {
$HostName = $HostName -replace "tcp:", ""
}
if ($HostName -like ".") {
$pos = $HostName.IndexOf(".")
$HostName = $HostName.Substring(0, $pos)
}
}
else {
$InstName = $ServerName
$HostName = $ServerName
}
if ($HostName -like "tcp:*") {
$HostName = $HostName -replace "tcp:", ""
}
if ($HostName -like ".") {
$pos = $HostName.IndexOf(".")
$HostName = $HostName.Substring(0, $pos)
}
#Return help menu if $ServerName is ? or Help
if ("?", "Help" -Contains $ServerName) {
Get-PSBlitzHelp
Read-Host -Prompt "Press Enter to close this window."
Exit
}
##Have sp_BlitzIndex, sp_BlitzCache, sp_BlitzLock executed against a specific database
if ($IsAzure -eq $false) {
$CheckDB = Read-Host -Prompt "Name of the database you want to check (leave empty for all)"
}
##SQL Login
$SQLLogin = Read-Host -Prompt "SQL login name (leave empty to use integrated security)"
if (!([string]::IsNullOrEmpty($SQLLogin))) {
##SQL Login pass
$SecSQLPass = Read-Host -Prompt "Password" -AsSecureString
}
##Indepth check
$IsIndepth = Read-Host -Prompt "Perform an in-depth check?[Y/N]"
##sp_BlitzWho delay
if (!([int]$BlitzWhoDelay = Read-Host "Seconds of delay between sp_BlizWho executions (empty defaults to 10)")) {
$BlitzWhoDelay = 10
}
##Output file type
if (!([string]$ToHTML = Read-Host -Prompt "Output the report as HTML instead of Excel?(empty defaults to N)[Y/N]")) {
$ToHTML = "N"
}
##Zip output files
if (!([string]$ZipOutput = Read-Host -Prompt "Create a zip archive of the output files?(empty defaults to N)[Y/N]")) {
$ZipOutput = "N"
}
}
else {
$InteractiveMode = 0
if ($ServerName -like "*\*") {
$pos = $ServerName.IndexOf("\")
$InstName = $ServerName.Substring($pos + 1)
$HostName = $ServerName.Substring(0, $pos)
}
#Azure SQL DB
elseif ($ServerName -like "*database.windows.net*") {
$IsAzure = $true
#let's strip "tcp: first just in case"
if ($ServerName -like "tcp:*") {
$TCPStripped = $true
$ServerName = $ServerName -replace "tcp:", ""
}
#get the database name if it was provided
if ($ServerName -like "*:*") {
$pos = $ServerName.IndexOf(":")
[string]$ASDBName = $ServerName.Substring($pos + 1)
$ServerName = $ServerName.Substring(0, $pos)
if (!([string]::IsNullOrEmpty($ASDBName))) {
$IsAzureSQLDB = $true
}
}
#Get the hostname
if ($ServerName -like "*,*") {
$pos = $ServerName.IndexOf(",")
$HostName = $ServerName.Substring(0, $pos)
}
else {
$HostName = $ServerName
}
$InstName = $HostName
#slap tcp: back on because why not
if ($TCPStripped) {
$ServerName = "tcp:$ServerName"
}
}
elseif ($ServerName -like "*,*") {
$pos = $ServerName.IndexOf(",")
$HostName = $ServerName.Substring(0, $pos)
$InstName = $ServerName -replace ",", "-"
}
else {
$InstName = $ServerName
$HostName = $ServerName
}
}
if (($InteractiveMode -eq 0) -and (!([string]::IsNullOrEmpty($SQLLogin))) -and ([string]::IsNullOrEmpty($SQLPass))) {
Write-Host " You've provided a SQL login, but no password." -Fore Yellow
$SecSQLPass = Read-Host -Prompt "Password" -AsSecureString
#Convert the secure password to plain text for SqlConnection
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecSQLPass)
$SQLPass = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
#Convert the secure password to plain text for SqlConnection
if (($InteractiveMode -eq 1) -and (!([string]::IsNullOrEmpty($SQLLogin))) ) {
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecSQLPass)
$SQLPass = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
}
###If release is older than 2 months print an info message
if ($NowDate -ge $TwoMonthsFromRelease) {
Write-Host "Informational: This release of PSBlitz is two months old" -Fore Yellow
Write-Host "->You can check for a newer release at https://github.com/VladDBA/PSBlitz/releases"
}
### If Azure and database name was not provided, do a preliminary test for the type of env
#Turning this into a fallback check in case the server name doesn't match the standard Azure SQL format
if (($IsAzure -eq $false) -and ([string]::IsNullOrEmpty($ASDBName)) -and ($IsAzureSQLDB -eq $false)) {
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$AppName = "PSBlitz " + $Vers
if (!([string]::IsNullOrEmpty($SQLLogin))) {
$ConnString = "Server=$ServerName;Database=master;User Id=$SQLLogin;Password=$SQLPass;Connection Timeout=$ConnTimeout;Application Name=$AppName"
}
else {
$ConnString = "Server=$ServerName;Database=master;trusted_connection=true;Connection Timeout=$ConnTimeout;Application Name=$AppName"
}
$SqlConnection.ConnectionString = $ConnString