-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPSBlitz.ps1
3791 lines (3519 loc) · 139 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
<# PSBlitz.ps1
For updates/info visit https://github.com/VladDBA/PSBlitz
#Usage Examples:
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.
1. Print the help menu
.\PSBlitz.ps1 ?
or
.\PSBlitz.ps1 Help
2. Run it against the whole instance (named instance SQL01), with default checks via integrated security
.\PSBlitz.ps1 Server01\SQL01
3. Run it against the whole instance listening on port 1433 on host Server01, with default checks via integrated security
.\PSBlitz.ps1 Server01,1433
4. Run it against the whole instance, with in-depth checks via integrated security
.\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y
5. Run it with in-depth checks, limit sp_BlitzIndex, sp_BlitzCache, and sp_BlitzLock to YourDatabase only, via integrated security
.\PSBlitz.ps1 Server01\SQL01 -IsIndepth Y -CheckDB YourDatabase
6. Run it against the whole instance, with default checks via SQL login and password
.\PSBlitz.ps1 Server01\SQL01 -SQLLogin DBA1 -SQLPass SuperSecurePassword
7. 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
.\PSBlitz.ps1 Server02 -SQLLogin DBA1 -SQLPass SuperSecurePassword -IsIndepth Y -CheckDB YourDatabase
Note that -ServerName is a positional parameter, so you don't necessarily have to specify the parameter's name as long as the first thing after the script's name is the instance or a question mark
#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 is held by Vlad Drumea, 2023 as described below.
Copyright (c) 2023 Vlad Drumea
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.
#>
###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 = 800,
[Parameter(Mandatory = $False)]
[int]$ConnTimeout = 15,
[Parameter(Mandatory = $False)]
[string]$OutputDir,
[Parameter(Mandatory = $False)]
[string]$ToHTML = "N",
[Parameter(Mandatory = $False)]
[string]$ZipOutput = "N"
)
###Internal params
#Version
$Vers = "3.1.1"
$VersDate = "20230508"
#Get script path
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
#Set resources path
$ResourcesPath = $ScriptPath + "\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",
"GetStatsAndIndexInfoForWholeDB.sql",
"GetBlitzWhoData.sql", "GetInstanceInfo.sql",
"GetTempDBUsageInfo.sql")
#Set path+name of the input Excel file
$OrigExcelF = $ResourcesPath + "\" + $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
-MaxTimeout - can be used to set a higher timeout for sp_BlitzIndex and Stats and Index info
retrieval. Defaults to 800 (13.3 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 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
`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 " ->Running sp_BlitzWho - pass $BlitzWhoPass... " -NoNewLine
}
else {
Write-Host " Running sp_BlitzWho - pass $BlitzWhoPass... " -NoNewLine
}
$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
}
Catch {
Write-Host @RedX
}
}
#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 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
}
}
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
}
}
}
function Get-ExecTime {
$StepRunTime = (New-TimeSpan -Start $StepStart -End $StepEnd).TotalSeconds
return [Math]::Round($StepRunTime, 2)
}
###Job preparation
#sp_BlitzWho
$InitScriptBlock = {
function Invoke-BlitzWho {
param (
[string]$BlitzWhoQuery
)
$BlitzWhoCommand = new-object System.Data.SqlClient.SqlCommand
$BlitzWhoCommand.CommandText = $BlitzWhoQuery
$BlitzWhoCommand.CommandTimeout = 20
$SqlConnection.Open()
$BlitzWhoCommand.Connection = $SqlConnection
$BlitzWhoCommand.ExecuteNonQuery() | Out-Null
$SqlConnection.Close()
}
function Invoke-FlagTableCheck {
param (
[string]$FlagTblDt
)
$CheckFlagTblQuery = new-object System.Data.SqlClient.SqlCommand
$FlagTblQuery = "SELECT CASE `nWHEN OBJECT_ID(N'tempdb.dbo.BlitzWhoOutFlag_$FlagTblDt', N'U') "
$FlagTblQuery = $FlagTblQuery + "IS NOT NULL THEN 'Y' `nELSE 'N' `nEND 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 = "DROP TABLE tempdb.dbo.BlitzWhoOutFlag_$FlagTblDt;"
$CleanupCommand.CommandText = $Cleanup
$CleanupCommand.CommandTimeout = 20
$SqlConnection.Open()
$CleanupCommand.Connection = $SqlConnection
$CleanupCommand.ExecuteNonQuery() | Out-Null
$SqlConnection.Close()
}
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) {
if ($SuccessCount -gt 0) {
Write-Host " ->Successful runs: $SuccessCount" -NoNewLine
}
Write-Host "; Failed runs: $FailedCount" -NoNewLine
if ($FlagCheckRetry -gt 0) {
Write-Host "; Retries: $FlagCheckRetry"
}
else {
Write-Host ""
}
}
else {
Write-Host " ->Successful runs: $SuccessCount" -NoNewLine
if ($FlagCheckRetry -gt 0) {
Write-Host "; Consecutive retries: $FlagCheckRetry"
}
else {
Write-Host ""
}
}
}
###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 = $ResourcesPath + "\" + $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
}
###Switch to interactive mode if $ServerName is empty
if ([string]::IsNullOrEmpty($ServerName)) {
Write-Host "Running in interactive mode"
$InteractiveMode = 1
##Instance
$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)
}
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
$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
$SQLPass = Read-Host -Prompt "Password "
}
##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)
}
elseif ($ServerName -like "*,*") {
$pos = $ServerName.IndexOf(",")
$HostName = $ServerName.Substring(0, $pos)
$InstName = $ServerName -replace ",", "-"
}
else {
$InstName = $ServerName
$HostName = $ServerName
}
}
#Set the string to replace for $CheckDB
if (!([string]::IsNullOrEmpty($CheckDB))) {
$OldCheckDBStr = ";SET @DatabaseName = NULL;"
$NewCheckDBStr = ";SET @DatabaseName = '" + $CheckDB + "';"
}
###Define connection
$AppName = "PSBlitz " + $Vers
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
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
###Test connection to instance
[int]$CmdTimeout = 100
Write-Host "Testing connection to instance $ServerName... " -NoNewLine
$ConnCheckQuery = new-object System.Data.SqlClient.SqlCommand
$Query = "SELECT GETDATE();"
$ConnCheckQuery.CommandText = $Query
$ConnCheckQuery.Connection = $SqlConnection
$ConnCheckQuery.CommandTimeout = $CmdTimeout
$ConnCheckAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$ConnCheckAdapter.SelectCommand = $ConnCheckQuery
$ConnCheckSet = new-object System.Data.DataSet
Try {
$StepStart = get-date
$ConnCheckAdapter.Fill($ConnCheckSet) | Out-Null -ErrorAction Stop
$SqlConnection.Close()
$StepEnd = get-date
}
Catch {
$StepEnd = get-date
Invoke-ErrMsg
$Help = Read-Host -Prompt "Need help?[Y/N]"
if ($Help -eq "Y") {
Get-PSBlitzHelp
#Don't close the window automatically if in interactive mode
if ($InteractiveMode -eq 1) {
Read-Host -Prompt "Press Enter to close this window."
Exit
}
}
else {
Exit
}
}
if ($ConnCheckSet.Tables[0].Rows.Count -eq 1) {
Write-Host @GreenCheck
$StepRunTime = (New-TimeSpan -Start $StepStart -End $StepEnd).TotalSeconds
$ConnTest = [Math]::Round($StepRunTime, 3)
if ($DebugInfo) {
Write-Host " - $ConnTest seconds"
}
else {
if ($ConnTest -ge 2) {
Write-Host "->Estimated response latency: $ConnTest seconds" -Fore Red
}
elseif ($ConnTest -ge 0.5) {
Write-Host "->Estimated response latency: $ConnTest seconds" -Fore Yellow
}
elseif ($ConnTest -ge 0.2) {
Write-Host "->Estimated response latency: $ConnTest seconds"
}
elseif ($ConnTest -lt 0.2) {
Write-Host "->Estimated response latency: $ConnTest seconds" -Fore Green
}
}
}
###Test existence of value provided for $CheckDB
if (!([string]::IsNullOrEmpty($CheckDB))) {
Write-Host "Checking existence of database $CheckDB..."
$CheckDBQuery = new-object System.Data.SqlClient.SqlCommand
$DBQuery = "SELECT [name] from sys.databases WHERE [name] = @DBName AND [state] = 0;"
$CheckDBQuery.CommandText = $DBQuery
$CheckDBQuery.Parameters.Add("@DBName", [Data.SQLDBType]::NVarChar, 256) | Out-Null
$CheckDBQuery.Parameters["@DBName"].Value = $CheckDB
$CheckDBQuery.Connection = $SqlConnection
$CheckDBQuery.CommandTimeout = 100
$CheckDBAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$CheckDBAdapter.SelectCommand = $CheckDBQuery
$CheckDBSet = new-object System.Data.DataSet
$CheckDBAdapter.Fill($CheckDBSet) | Out-Null
$SqlConnection.Close()
Try {
if ($CheckDBSet.Tables[0].Rows[0]["name"] -eq $CheckDB) {
Write-Host "->Database $CheckDB - " -NoNewLine -ErrorAction Stop
Write-Host "is online" -fore green -ErrorAction Stop
}
}
Catch {
Write-Host "->Database $CheckDB either does not exist or is offline" -fore red
$InstanceWide = Read-Host -Prompt "Switch to instance-wide plan cache, index, and deadlock check?[Y/N]"
if ($InstanceWide -eq "Y") {
$CheckDB = ""
}
else {
$Help = Read-Host -Prompt "Need help?[Y/N]"
if ($Help -eq "Y") {
Get-PSBlitzHelp
#Don't close the window automatically if in interactive mode
if ($InteractiveMode -eq 1) {
Read-Host -Prompt "Press Enter to close this window."
Exit
}
}
else {
Exit
}
}
}
}
###Create directories
#Turn current date time into string for output directory name
$sdate = get-date
$DirDate = $sdate.ToString("yyyyMMddHHmm")
#Set output directory
#if (!([string]::IsNullOrEmpty($CheckDB))) {
# $OutDir = $scriptPath + "\" + $HostName + "_" + $InstName + "_" + $CheckDB + "_" + $DirDate
#}
#else {
# $OutDir = $scriptPath + "\" + $HostName + "_" + $InstName + "_" + $DirDate
#}
if ((!([string]::IsNullOrEmpty($OutputDir))) -and (Test-Path $OutputDir)) {
if ($OutputDir -notlike "*\") {
$OutputDir = $OutputDir + "\"
}
if (!([string]::IsNullOrEmpty($CheckDB))) {
$OutDir = $OutputDir + $HostName + "_" + $InstName + "_" + $CheckDB + "_" + $DirDate
}
else {
$OutDir = $OutputDir + $HostName + "_" + $InstName + "_" + $DirDate
}
}
else {
if (!([string]::IsNullOrEmpty($CheckDB))) {
$OutDir = $scriptPath + "\" + $HostName + "_" + $InstName + "_" + $CheckDB + "_" + $DirDate
}
else {
$OutDir = $scriptPath + "\" + $HostName + "_" + $InstName + "_" + $DirDate
}
}
if ($ZipOutput -eq "Y") {
if (!([string]::IsNullOrEmpty($CheckDB))) {
$ZipFile = $HostName + "_" + $InstName + "_" + $CheckDB + "_" + $DirDate + ".zip"
}
else {
$ZipFile = $HostName + "_" + $InstName + "_" + $DirDate + ".zip"
}
}
if ($DebugInfo) {
Write-Host " Output directory: $OutDir" -Fore Yellow
}
#Check if output directory exists
if (!(Test-Path $OutDir)) {
New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
}
#Set plan output directory
$PlanOutDir = $OutDir + "\" + "Plans"
#Check if plan output directory exists
if (!(Test-Path $PlanOutDir)) {
New-Item -ItemType Directory -Force -Path $PlanOutDir | Out-Null
}
#Set deadlock graph output directory
$XDLOutDir = $OutDir + "\" + "Deadlocks"
#Check if deadlock graph output directory exists
if (!(Test-Path $XDLOutDir)) {
New-Item -ItemType Directory -Force -Path $XDLOutDir | Out-Null
}
#Initiate Excel app here
if ($ToHTML -ne "Y") {
###Open Excel
if ($DebugInfo) {
$ErrorActionPreference = "Continue"
Write-Host "Opening excel file" -fore yellow
}
else {
#Do not display the occasional "out of memory" errors
$ErrorActionPreference = "SilentlyContinue"
}
try {
$ExcelApp = New-Object -comobject Excel.Application -ErrorAction Stop
}
catch {
Write-Host "Could not open Excel." -fore Red
Write-Host "->Switching to HTML output."
$ToHTML = "Y"
$ErrorActionPreference = "Continue"
}
}
if ($ToHTML -eq "Y") {
#Set HTML files output directory
$HTMLOutDir = $OutDir + "\" + "HTMLFiles"
if (!(Test-Path $HTMLOutDir)) {
New-Item -ItemType Directory -Force -Path $HTMLOutDir | Out-Null
}
$HTMLPre = @"
<!DOCTYPE html>
<html>
<head>
<style>
body
{
background-color:#FFFFFF;
font-family:Tahoma;
font-size:11pt;
}
table {
margin-left: auto;
margin-right: auto;
border-spacing: 1px;
}
th {
background-color: dodgerblue;
color: white;
font-weight: bold;
padding: 5px;
text-align: center;
border: 1px solid black;
}
td {
padding: 5px;
border: 1px solid black;
vertical-align: top;
}
td:first-child {
font-weight: bold;
text-align: center;
}
h1 {
text-align: center;
}
h2 {
test-align: Left;
}
</style>
"@
$URLRegex = '(?i)\b((?:https?://|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\".,<>?«»“”]))'
}
else {
###Set output Excel name and destination
if (!([string]::IsNullOrEmpty($CheckDB))) {
$OutExcelFName = "Active_$InstName_$CheckDB.xlsx"
}
else {
$OutExcelFName = "Active_$InstName.xlsx"
}
$OutExcelF = $OutDir + "\" + $OutExcelFName
###Copy Excel template to output directory
<#
This is a fix for https://github.com/VladDBA/PSBlitz/issues/4
#>
Copy-Item $OrigExcelF -Destination $OutExcelF
}
#Set output table for sp_BlitzWho
#Set replace strings
$OldBlitzWhoOut = "@OutputTableName = 'BlitzWho_..PSBlitzReplace..',"
$NewBlitzWhoOut = "@OutputTableName = 'BlitzWho_$DirDate',"
if ($ToHTML -ne "Y") {
###Open Excel FIle
if ($DebugInfo) {
$ExcelApp.visible = $True
}
else {
$ExcelApp.visible = $False
}
$ExcelFile = $ExcelApp.Workbooks.Open("$OutExcelF")
$ExcelApp.DisplayAlerts = $False
}
###Check instance uptime
$UptimeQuery = new-object System.Data.SqlClient.SqlCommand
$Query = "SELECT CAST(DATEDIFF(HH, [sqlserver_start_time], GETDATE()) / 24.00 AS NUMERIC(23, 2)) AS [uptime_days] "
$Query = $Query + "`nFROM [sys].[dm_os_sys_info];"
$UptimeQuery.CommandText = $Query
$UptimeQuery.Connection = $SqlConnection
$UptimeQuery.CommandTimeout = 100
$UptimeAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$UptimeAdapter.SelectCommand = $UptimeQuery
$UptimeSet = new-object System.Data.DataSet
$UptimeAdapter.Fill($UptimeSet) | Out-Null
$SqlConnection.Close()
if ($UptimeSet.Tables[0].Rows[0]["uptime_days"] -lt 7.00) {
[string]$DaysUp = $UptimeSet.Tables[0].Rows[0]["uptime_days"]
Write-Host "Warning: Instance uptime is less than 7 days - $DaysUp" -Fore Red
Write-Host "->Diagnostics data might not be reliable with less than 7 days of uptime." -Fore Red
}
#####################################################################################
# Check start #
#####################################################################################
try {
###Set completion flag
$TryCompleted = "N"
Write-Host $("-" * 80)
Write-Host " Starting" -NoNewLine
if ($IsIndepth -eq "Y") {
Write-Host " in-depth" -NoNewLine
}
if (!([string]::IsNullOrEmpty($CheckDB))) {
Write-Host " database-specific" -NoNewLine
}
Write-Host " check for $ServerName"
Write-Host $("-" * 80)
if (($DebugInfo) -and ($MaxTimeout -ne 800)) {
Write-Host " ->MaxTimeout has been set to $MaxTimeout"
}
###Load sp_BlitzWho in memory
[string]$Query = [System.IO.File]::ReadAllText("$ResourcesPath\spBlitzWho_NonSPLatest.sql")
#Replace output table name
[string]$BlitzWhoRepl = $Query -replace $OldBlitzWhoOut, $NewBlitzWhoOut
###Execution start time
$StartDate = get-date
###Collecting first pass of sp_BlitzWho data
$JobName = "BlitzWho"
Write-Host " Starting BlitzWho background process... " -NoNewline
$Job = Start-Job -Name $JobName -InitializationScript $InitScriptBlock -ScriptBlock $MainScriptblock -ArgumentList $ConnString, $BlitzWhoRepl, $DirDate, $BlitzWhoDelay
$JobStatus = $Job | Select-Object -ExpandProperty State
if ($JobStatus -ne "Running") {
Write-Host @RedX
if ($DebugInfo) {
Write-Host ""
}
Write-Host " ->Switching to foreground execution."
Invoke-BlitzWho -BlitzWhoQuery $BlitzWhoRepl -IsInLoop N
$BlitzWhoPass += 1
}
else {
Write-Host @GreenCheck
if ($DebugInfo) {
Write-Host ""
}
Write-Host " ->sp_BlitzWho will collect data every $BlitzWhoDelay seconds."
}
#####################################################################################
# Instance Info #
#####################################################################################
Write-Host " Retrieving instance information... " -NoNewLine
$CmdTimeout = 600
[string]$Query = [System.IO.File]::ReadAllText("$ResourcesPath\GetInstanceInfo.sql")
$InstanceInfoQuery = new-object System.Data.SqlClient.SqlCommand
$InstanceInfoQuery.CommandText = $Query
$InstanceInfoQuery.Connection = $SqlConnection
$InstanceInfoQuery.CommandTimeout = $CmdTimeout
$InstanceInfoAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$InstanceInfoAdapter.SelectCommand = $InstanceInfoQuery
$InstanceInfoSet = new-object System.Data.DataSet
try {
$StepStart = get-date
$InstanceInfoAdapter.Fill($InstanceInfoSet) | Out-Null -ErrorAction Stop
$SqlConnection.Close()
$StepEnd = get-date
Write-Host @GreenCheck
$StepRunTime = (New-TimeSpan -Start $StepStart -End $StepEnd).TotalSeconds
$RunTime = [Math]::Round($StepRunTime, 2)
if ($DebugInfo) {
Write-Host " - $RunTime seconds" -Fore Yellow
}
$StepOutcome = "Success"
}
Catch {
$StepEnd = get-date
Invoke-ErrMsg
$StepOutcome = "Failure"
}
if ($StepOutcome -eq "Success") {
$InstanceInfoTbl = New-Object System.Data.DataTable
$InstanceInfoTbl = $InstanceInfoSet.Tables[0]
$ResourceInfoTbl = New-Object System.Data.DataTable
$ResourceInfoTbl = $InstanceInfoSet.Tables[1]
if ($ToHTML -eq "Y") {
if ($DebugInfo) {
Write-Host " ->Converting instance info to HTML" -fore yellow
}
$InstanceInfoTbl.Columns.Add("Estimated Response Latency (Sec)", [decimal]) | Out-Null
$InstanceInfoTbl.Rows[0]["Estimated Response Latency (Sec)"] = $ConnTest
$htmlTable1 = $InstanceInfoTbl | Select-Object @{Name = "Machine Name"; Expression = { $_."machine_name" } },
@{Name = "Instance Name"; Expression = { $_."instance_name" } },
@{Name = "Version"; Expression = { $_."product_version" } },
@{Name = "Product Level"; Expression = { $_."product_level" } },
@{Name = "Patch Level"; Expression = { $_."patch_level" } },
@{Name = "Edition"; Expression = { $_."edition" } },
@{Name = "Is Clustered?"; Expression = { $_."is_clustered" } },
@{Name = "Is AlwaysOnAG?"; Expression = { $_."always_on_enabled" } },
@{Name = "Last Startup"; Expression = { $_."instance_last_startup" } },
@{Name = "Uptime (days)"; Expression = { $_."uptime_days" } },
"Estimated Response Latency (Sec)" | ConvertTo-Html -As Table -Fragment
if ($DebugInfo) {
Write-Host " ->Converting resource info to HTML" -fore yellow
}
$htmlTable2 = $ResourceInfoTbl | Select-Object @{Name = "Logical Cores"; Expression = { $_."logical_cpu_cores" } },
@{Name = "Physical Cores"; Expression = { $_."physical_cpu_cores" } },
@{Name = "Physical memory GB"; Expression = { $_."physical_memory_GB" } },
@{Name = "Max Server Memory GB"; Expression = { $_."max_server_memory_GB" } },
@{Name = "Target Server Memory GB"; Expression = { $_."target_server_memory_GB" } },
@{Name = "Total Memory Used GB"; Expression = { $_."total_memory_used_GB" } } | ConvertTo-Html -As Table -Fragment
$HtmlTabName = "Instance Overview"
$html = $HTMLPre + @"
<title>$HtmlTabName</title>
</head>
<body>
<h1>$HtmlTabName</h1>
<h2 style="text-align: center;">Instance information</h2>
$htmlTable1
<b>
<h2 style="text-align: center;">Resource information</h2>
$htmlTable2
</body>
</html>
"@
if ($DebugInfo) {
Write-Host " ->Writing HTML file." -fore yellow
}
$html | Out-File -Encoding utf8 -FilePath "$HTMLOutDir\InstanceInfo.html"
}
else {
###Populating the "Instance Info" sheet
$ExcelSheet = $ExcelFile.Worksheets.Item("Instance Info")
##Instance Info section
#Specify at which row in the sheet to start adding the data