-
Notifications
You must be signed in to change notification settings - Fork 63
/
Test-EnterpriseDnsHealth.ps1
1563 lines (1447 loc) · 70.1 KB
/
Test-EnterpriseDnsHealth.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
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# THIS SAMPLE CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
# WHETHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
# IF THIS CODE AND INFORMATION IS MODIFIED, THE ENTIRE RISK OF USE OR RESULTS IN
# CONNECTION WITH THE USE OF THIS CODE AND INFORMATION REMAINS WITH THE USER.
<#
.SYNOPSIS
This script will help DNS administrator to ensure that all the DNS servers that are configured on
clients as DNS servers are able to resolve all the required zones (corpnet & Internet). Additionally,
it’ll also verify health of other DNS resources (Forwarders, RootHints, Zone Delegations, Zone Aging
settings etc.) and generate consolidated reports, which can be used for further investigation purpose.
.DESCRIPTION
This script performs a health check of the Enterprise DNS servers configuration.
.PARAMETER ValidationType
Define valdation type: All, Domain, Zone, ZoneAging, ZoneDelegation, Forwarder, RootHints
.PARAMETER Path
Full path of cache files.
If the Path parameter is not specified, the current directory is used.
.PARAMETER CleanUpOldCacheFiles
Clean-Up old cache files.
.PARAMETER CleanUpOldReports
Clean-Up old report files.
.PARAMETER Force
Applicable with CleanUpOldCacheFiles & CleanUpOldReports switches and deletes the files without user confirmation.
.PARAMETER DnsServerList
List of name resolvers on which health check need to be performed.
.PARAMETER,DomainList
List of all available root domains across the enterprise.
.PARAMETER ZoneList
List of zones to be verified.
.PARAMETER ZoneHostingServerList
List of zone hosting servers, which hosts one or more zones.
.PARAMETER DhcpServerList
List of DHCP servers across the enterprise.
.NOTES
- Requires Windows Server 2012 or Windows 8 with Remote Server Administration Tools.
- Requires read access across all enterprise resources such as AD, DHCP & DNS Servers.
- Requires the PowerShell modules: DNSServer, DHCPServer (Only if DNS server list isn't specified through text file)
& ActiveDirectory (Only if domain list isn't specified through text file).
Basically below RSAT tools should be installed:
[X] DNS Server Tools RSAT-DNS-Server Installed
[X] DHCP Server Tools RSAT-DHCP Installed
[X] Active Directory module for Windows PowerShell RSAT-AD-PowerShell Installed
.EXAMPLE
Test-EnterpriseDnsHealth All -Verbose
Performs a health check of below resources and prints verbose messages on PS console:
1. Root Domain Zones or Non-Root Domain zones across all DNS servers.
2. Zone aging configuration across all zone hosting servers.
3. Configured delegation across all zones.
4. All configured Forwarders across all DNS servers.
5. All configured RootHints across all DNS servers.
Test-EnterpriseDnsHealth -ValidationType All –DhcpServerList Dhcp1.contoso.com, Dhcp2.contoso.com –Verbose
Will perform a health check of all the resources and prints verbose messages on PS console.
It’ll fetch information about DNS servers from Dhcp1.contoso.com & Dhcp2.contoso.com DHCP servers
(If DnsServerList.txt is unavailable).
Test-EnterpriseDnsHealth @("Zone", "Domain") –ZoneHostingServerList Srv1.contoso.com,Srv2.contoso.com
Will perform a health check of Zones (all the zones hosted on Srv1.contoso.com,Srv2.contoso.com
– If ZoneList.txt is unavailable) & Domains resources.
Test-EnterpriseDnsHealth ZoneAging,ZoneDelegation -CleanUpOldCacheFiles -ZoneList Zone1.contoso.com,Zone2.contoso.com
Will perform a health check of ZoneAging & ZoneDelegation inside zones Zone1.contoso.com & Zone2.contoso.com
and deletes the old caches with user confirmation before validation.
Test-EnterpriseDnsHealth Forwarder,RootHints –CleanUpOldCacheFiles –CleanUpOldReports –Force –DnsServerList Dns1.contoso.com,Dns2.contoso.com
Will perform a health check of Forwarder & RootHints configured at Dns1.contoso.com & Dns2.contoso.com DNS servers
and deletes the old caches & reports without user confirmation before validation.
#>
Param
(
[parameter(Mandatory=$true, Position=0, HelpMessage="Define valdation type: All, Domain, Zone, ZoneAging, ZoneDelegation, Forwarder, RootHints")]
[Alias("Type")]
[String[]] $ValidationType,
[parameter(Mandatory=$false, Position=1, HelpMessage="Full path of cache files.")]
[String] $Path = $pwd.path + "\",
[parameter(Mandatory=$false, HelpMessage="Clean-Up old cache files.")]
[Switch] $CleanUpOldCacheFiles,
[parameter(Mandatory=$false, HelpMessage="Clean-Up old report files.")]
[Switch] $CleanUpOldReports,
[parameter(Mandatory=$false, HelpMessage="Applicable with CleanUpOldCacheFiles & CleanUpOldReports switches and deletes the files without user confirmation.")]
[Switch] $Force,
[parameter(Mandatory=$false, HelpMessage="List of name resolvers on which health check need to be performed.")]
[String[]] $DnsServerList = $null,
[parameter(Mandatory=$false, HelpMessage="List of all available root domains across the enterprise.")]
[String[]] $DomainList = $null,
[parameter(Mandatory=$false, HelpMessage="List of zones to be verified.")]
[String[]] $ZoneList = $null,
[parameter(Mandatory=$false, HelpMessage="List of zone hosting servers, which hosts one or more zones.")]
[String[]] $ZoneHostingServerList = $null,
[parameter(Mandatory=$false, HelpMessage="List of DHCP servers across the enterprise.")]
[String[]] $DhcpServerList = $null
)
#
# Enable strict mode parsing
#
Set-StrictMode -Version 2
#
# Import the required PowerShell modules
#
Import-Module DNSServer -ErrorAction Ignore
Import-Module DHCPServer -ErrorAction Ignore
Import-Module ActiveDirectory -ErrorAction Ignore
if (-not (Get-Module DNSServer)) {
throw 'The Windows Feature "DNS Server Tools" is not installed. `
(On server SKU run "Install-WindowsFeature -Name RSAT-DNS-Server", on client SKU install RSAT client)'
}
#
# Initialize global params
#
$script:validValidationTypes = @("Domain", "Zone", "ZoneAging", "ZoneDelegation", "Forwarder", "RootHints");
$script:allValidationType = "All";
$script:switchParamVal = "__SWITCH__";
$script:cmdLetReturnedStatus = $null;
$script:dnsServerList = $DnsServerList;
$script:domainList = $DomainList;
$script:zoneList = $ZoneList;
$script:zoneHostingServerList = $ZoneHostingServerList;
$script:dhcpServerList = $DhcpServerList;
$script:dnsServerListFilePath = $Path + "DnsServerList.txt";
$script:domainListFilePath = $Path + "DomainList.txt";
$script:zoneListFilePath = $Path + "ZoneList.txt";
$script:zoneHostingServerListFilePath = $Path + "ZoneHostingServerList.txt";
$script:dhcpServerListFilePath = $Path + "DhcpServerList.txt";
$script:domainAndHostingServersList = $null;
$script:zoneAndHostingServersList = $null;
#
# Check if old cache files already exist and user has asked to delete it.
#
if ($CleanUpOldCacheFiles -and (Test-Path -Path ($Path + "*.txt") -PathType Leaf))
{
if ($Force) {
Remove-Item -Path ($Path + "*.txt") -Force;
} else {
Remove-Item -Path ($Path + "*.txt") -Confirm;
}
}
#
# Check if old reports already exist and user has asked to delete it.
#
if ($CleanUpOldReports -and (Test-Path -Path ($Path + "*.html") -PathType Leaf))
{
if ($Force) {
Remove-Item -Path ($Path + "*.html") -Force;
} else {
Remove-Item -Path ($Path + "*.html") -Confirm;
}
}
#
# Log levels to log messages
#
$script:logLevel = @{
"Verbose" = [int]1
;"Host" = [int]2
;"Warning" = [int]3
;"Error" = [int]4
}
#
# Output report view
#
$script:resultView =@{
"List" = "List"
;"Table" = "Table"
}
#
# Logs comments as per input log level
#
Function LogComment
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$message,
[int]$level = $script:logLevel.Verbose
)
$message = ([DateTime]::Now).ToString() + ": " + $message;
switch ($level)
{
$script:logLevel.Verbose {Write-Verbose $message};
$script:logLevel.Host {Write-Host -ForegroundColor Cyan $message};
$script:logLevel.Warning {Write-Warning $message};
$script:logLevel.Error {Write-Error $message};
default {throw "Not a valid log level: " + $level};
}
}
#
# Accepts CmdLet name & param hash and executes the CmdLet.
# All methods in this script will call this method to execute any CmdLet.
#
Function ExecuteCmdLet
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$cmdLetName,
[HashTable]$params = @{}
)
$cmdString=$cmdLetName;
$displayString=$cmdLetName;
$script:cmdLetReturnedStatus = [RetStatus]::Success;
if ($null -ne $params) {
foreach($key in $params.keys) {
if ($script:switchParamVal -eq $params[$key]) {
$cmdString +=" -$key ";
$displayString +=" -$key ";
} else {
$cmdString += " -$key `$params[`"$key`"]";
$displayString += " -$key $($params[$key])";
}
}
}
$cmdString += " -ErrorAction Stop 2> `$null";
$displayString += " -ErrorAction Stop 2> `$null";
LogComment $displayString $script:logLevel.Host;
$retObj = $null;
try {
$retObj = Invoke-Expression $cmdString;
} catch [Exception] {
if (Get-Member -InputObject $_.Exception -Name "Errordata")
{
# Handling DNS server module specific exceptions.
if (5 -eq $_.Exception.Errordata.error_Code) {
LogComment $("Caught error: Access is denied, considering it as current login creds don't have server read access.") `
$script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::AccessIsDenied;
} elseif (1722 -eq $_.Exception.Errordata.error_Code) {
LogComment $("Caught error: The RPC server is unavailable, considering it as server is down.") `
$script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::RpcServerIsUnavailable;
} elseif (9601 -eq $_.Exception.Errordata.error_Code) {
LogComment $("Caught error: DNS zone does not exist, considering it as given server isn't hosting input zone.") `
$script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::ZoneDoesNotExist;
} elseif (9611 -eq $_.Exception.Errordata.error_Code) {
LogComment $("Caught error: Invalid DNS zone type, considering it as we can't perform current operation on input zone.") `
$script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::OperationIsNotSupported;
} elseif (9714 -eq $_.Exception.Errordata.error_Code) {
LogComment $("Caught error: DNS name does not exist, considering it as input record doesn't exist.") `
$script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::RecordDoesNotExist;
} else {
LogComment $("Caught error while executing '" + $displayString + "' with errorcode: " + $_.Exception.Errordata.error_Code) `
$script:logLevel.Error;
$script:cmdLetReturnedStatus = $([String]$_.Exception.Errordata.error_Code + ":" + $_.Exception.Errordata.error_WindowsErrorMessage);
#throw;
}
} elseif (Get-Member -InputObject $_ -Name "FullyQualifiedErrorId") {
# Handling Resolve-DnsName specific errors.
if ($_.FullyQualifiedErrorId.Contains("DNS_ERROR_RCODE_NAME_ERROR")) {
LogComment $("Caught error: ResolveDnsNameResolutionFailed in Resolve-DnsName.") $script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::ResolveDnsNameResolutionFailed;
} elseif ($_.FullyQualifiedErrorId.Contains("System.Net.Sockets.SocketException")) {
LogComment $("Caught error: ResolveDnsNameServerNotFound in Resolve-DnsName.") $script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::ResolveDnsNameServerNotFound;
} elseif ($_.FullyQualifiedErrorId.Contains("ERROR_TIMEOUT")) {
LogComment $("Caught error: ResolveDnsNameTimeoutPeriodExpired in Resolve-DnsName.") $script:logLevel.Warning;
$script:cmdLetReturnedStatus = [RetStatus]::ResolveDnsNameServerNotFound;
} else {
LogComment $("Caught error while executing '" + $displayString + "' `n" + $_.Exception) $script:logLevel.Error;
$script:cmdLetReturnedStatus = $([String]$_.FullyQualifiedErrorId + ":" + $_.Exception);
throw;
}
} else {
LogComment $("Caught error while executing '" + $displayString + "' `n" + $_.Exception) $script:logLevel.Error;
$script:cmdLetReturnedStatus = $($_.Exception);
throw;
}
}
if ($null -eq $retObj) {
LogComment "CmdLet returned with NULL..." $script:logLevel.Host;
}
return $retObj
}
#
# If $dnsServerListFromCmdLine is Non-NULL then it'll return with existing elements in $dnsServerListFromCmdLine.
# Else it'll try to load EnterpriseDnsServerList from $script:dnsServerListFilePath file.
# Even if it's unsuccessful then extracts Dns Server List from DNS options
# configured on all DHCP scopes and servers in the enterprise
#
Function Get-EnterpriseDnsServerList
{
param (
$dnsServerListFilePath = $script:dnsServerListFilePath,
$dhcpServerListFilePath = $script:dhcpServerListFilePath,
$dnsServerListFromCmdLine = $script:dnsServerList
)
$dnsServerList = $null;
if ($null -eq $dnsServerListFromCmdLine) {
# Load the DNS servers from $dnsServerListFilePath, if exists.
$dnsServerList = Get-FileContent $dnsServerListFilePath;
} else {
$dnsServerList = $dnsServerListFromCmdLine;
}
if ($null -eq $dnsServerList) {
LogComment "Unable to load DNS servers from the cache. So loading from DHCP servers."
if (-not(Get-Module DHCPServer)) {
LogComment $('The Windows Feature "DHCP Server Tools" is not installed. `
(On server SKU run "Install-WindowsFeature -Name RSAT-DHCP", on client SKU install RSAT client)') `
$script:logLevel.Warning;
LogComment $("Skipping this step and returning with NULL DNS List.") $script:logLevel.Warning;
return $null;
}
#Get the DHCP server information
$dhcpServerList = Get-EnterpriseDhcpServerList $dhcpServerListFilePath;
if ($null -eq $dhcpServerList) {
LogComment $("No DHCP servers were found, returning with NULL DNS server list.") $script:logLevel.Warning;
return $null;
}
# Now load the DNS options configured on all DHCP scopes and servers in the enterprise
$optionList = @();
$v4Options = Get-EnterpriseDhcpv4OptionId $dhcpServerList $false;
$optionList += $v4Options;
$v4Options = Get-EnterpriseDhcpv4OptionId $dhcpServerList $true;
$optionList += $v4Options;
$v6Options = Get-EnterpriseDhcpv6OptionId $dhcpServerList $false;
$optionList += $v6Options;
$v6Options = Get-EnterpriseDhcpv6OptionId $dhcpServerList $true;
$optionList += $v6Options;
$optionList = $optionList | ?{-not([String]::IsNullOrEmpty($_))};
if ($null -eq $optionList) {
LogComment $("No DNS server found in configured DHCP options across all input DHCP servers, returning with NULL DNS server list.") $script:logLevel.Warning;
} else {
# Once done now consolidate the DNS servers in the enumerated options
$servers = @();
$optionList | %{ $servers += $_.Value };
$dnsServerList = $servers | sort -Unique;
ExecuteCmdLet "Set-Content" @{"Path" = $dnsServerListFilePath; "Value" = $dnsServerList};
}
}
return $dnsServerList;
}
#
# If $domainListFromCmdLine is Non-NULL then it'll return with existing elements in
# $domainListFromCmdLine. Else it'll try to load all the domains from $domainListFilePath.
# Even if it's unsuccessful then extracts Domain List from Get-ADForest CmdLet.
#
Function Get-EnterpriseDomainList
{
param (
$domainListFilePath = $script:domainListFilePath,
$domainListFromCmdLine = $script:domainList
)
$domainList = $null;
if ($null -eq $domainListFromCmdLine) {
# Load the domain list from $domainListFilePath, if exists.
$domainList = Get-FileContent $domainListFilePath;
} else {
$domainList = $domainListFromCmdLine;
}
if ($null -eq $domainList) {
LogComment "Failed to load domains from the file. So loading from AD.";
try {
if (Get-Module ActiveDirectory) {
$forestObj = ExecuteCmdLet "Get-ADForest";
if ($null -ne $forestObj) {
$domainList = $forestObj.Domains;
}
if ($null -ne $domainList) {
ExecuteCmdLet "Set-Content" @{"Path" = $domainListFilePath; "Value" = $domainList};
} else {
LogComment $("Unable to obtain domainList from Get-ADForest. Returning with NULL DomainList.") `
$script:logLevel.Warning;
}
} else {
LogComment $('The Windows Feature "Active Directory module for Windows PowerShell" is not installed. `
(On server SKU run "Install-WindowsFeature -Name RSAT-AD-PowerShell", on client SKU install RSAT client)') $script:logLevel.Warning;
LogComment $("Skipping this step and returning with NULL DomainList.") $script:logLevel.Warning;
}
} catch [Exception] {
LogComment $("Get-ADForest failed, Skipping this step and returning with NULL DomainList. `n" `
+ $_.Exception) $script:logLevel.Warning;
}
}
return $domainList;
}
#
# If $zoneListFromCmdLine is Non-NULL then it'll return with existing elements in
# $zoneListFromCmdLine. Else it'll try to load all the zones from $zoneListFilePath file.
#
Function Get-EnterpriseZoneList
{
param (
$zoneListFilePath = $script:zoneListFilePath,
$zoneListFromCmdLine = $script:zoneList
)
$zoneList = $null;
if ($null -eq $zoneListFromCmdLine) {
# Load the zone list from $zoneListFilePath, if exists.
$zoneList = Get-FileContent $zoneListFilePath;
} else {
$zoneList = $zoneListFromCmdLine;
}
return $zoneList;
}
#
# If $zoneHostingServerListFromCmdLine is Non-NULL then it'll return with existing elements in $zoneHostingServerListFromCmdLine.
# Else it'll try to load zoneHostingServerList from $zoneHostingServerListFilePath file.
# If unsuccessful then returns with $dnsServerList.
#
Function Get-EnterpriseZoneHostingServerList
{
param (
$zoneHostingServerListFilePath = $script:zoneHostingServerListFilePath,
$dnsServerList = $script:dnsServerList,
$zoneHostingServerListFromCmdLine = $script:zoneHostingServerList
)
$zoneHostingServerList = $null;
if ($null -eq $zoneHostingServerListFromCmdLine) {
# Load the zone hosting servers from $zoneHostingServerListFilePath, if exists.
LogComment $("Filling Zone Hosting Servers list from the file.");
$zoneHostingServerList = Get-FileContent $zoneHostingServerListFilePath;
} else {
$zoneHostingServerList = $zoneHostingServerListFromCmdLine;
}
if ($null -eq $zoneHostingServerList) {
# Return with DNS Server list.
LogComment $("Zone Hosting Servers list isn't available, returning with DNS Server list.");
$zoneHostingServerList = $dnsServerList;
}
return $zoneHostingServerList;
}
#
# If $dhcpServerListFromCmdLine is Non-NULL then it'll return with existing elements in $dhcpServerListFromCmdLine.
# Else it'll try to load all the DHCP servers from $dhcpServerListFilePath file.
# Even if it's unsuccessful then extracts DHCP Server List from AD with Get-DhcpServerInDC CmdLet.
#
Function Get-EnterpriseDhcpServerList
{
param (
$dhcpServerListFilePath = $script:dhcpServerListFilePath,
$dhcpServerListFromCmdLine = $script:dhcpServerList
)
$dhcpServerList = $null;
if ($null -eq $dhcpServerListFromCmdLine) {
# Load the DHCP servers from $dhcpServerListFilePath, if exists.
$dhcpServerList = Get-FileContent $dhcpServerListFilePath;
} else {
$dhcpServerList = $dhcpServerListFromCmdLine;
}
if ($null -eq $dhcpServerList) {
LogComment "Failed to load DHCP server list from the file. So loading from AD.";
$dhcpObjList = ExecuteCmdLet "Get-DhcpServerInDC";
foreach($dhcpObj in $dhcpObjList) {
if ($null -eq $dhcpServerList) {$dhcpServerList = @()};
$dhcpServerList += $dhcpObj.IPAddress;
}
}
return $dhcpServerList;
}
#
# Gets the domain list and for each domain it sends a NS lookup query to default DNS
# server and gathers all the servers hosted these domains.
# Returns with a HashTable of domians and servers which are hosting these domians.
#
Function Get-EnterpriseDomainAndHostingServersHash
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$domainHostingServers,
$domainListFilePath = $script:domainListFilePath
)
$domainAndHostingServersHash = $null;
# Load the domains from CmdLine or $domainListFilePath, if exists
# or collect all the domains from current forest.
$domainList = Get-EnterpriseDomainList $domainListFilePath;
if ($null -ne $domainList) {
#$domainAndHostingServersHash = Get-ServersHostingTheZones $domainList $domainHostingServers;
$domainAndHostingServersHash = @{};
foreach($domain in $domainList) {
$domainHostingServer = Get-ZoneHostingServerListFromNSRecords $domain;
$domainAndHostingServersHash.Add($domain, $domainHostingServer);
}
Write-HashTableInHtml $domainAndHostingServersHash "DomainAndHostingServersHash";
} else {
LogComment $("Failed to get domain list. So returning with NULL HashTable.") $script:logLevel.Warning;
}
return $domainAndHostingServersHash;
}
#
# Gets ZoneList and if it's NULL then enumerate all the zones (except auto-created and TrustAnchors zones) across
# all zoneHostingServerList. Returns with a HashTable of zones and servers which are hosting these zones.
#
Function Get-EnterpriseZoneAndHostingServersHash
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$zoneHostingServerList,
$zoneListFilePath = $script:zoneListFilePath
)
$zoneAndHostingServersHash = $null;
# Load the zones from CmdLine or $zoneListFilePath, if exists.
$zoneList = Get-EnterpriseZoneList $zoneListFilePath;
if ($null -ne $zoneList) {
$zoneAndHostingServersHash = Get-ServersHostingTheZones $zoneList $zoneHostingServerList;
} else {
LogComment $("Failed to load zones from the file. So loading it from zoneHostingServerList.");
if ($null -ne $zoneHostingServerList) {
$zoneAndHostingServersHash = Get-ZonesHostingOnServers $zoneHostingServerList;
Write-HashTableInHtml $zoneAndHostingServersHash "ZoneAndHostingServersHash";
} else {
LogComment $("Failed to get Zone Hosting Servers list. Returning with NULL.") $script:logLevel.Warning;
}
}
return $zoneAndHostingServersHash;
}
#
# Queries all the Zone hosting servers, if they host zones exists in input zone list.
# Prepares a HashTable of zones and zoneHostingServerList.
#
Function Get-ServersHostingTheZones
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$zoneList,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$zoneHostingServerList
)
$zoneAndHostingServersHash = $null;
foreach($zone in $zoneList) {
if ($null -eq $zoneAndHostingServersHash) {$zoneAndHostingServersHash = @{}};
if ($zoneAndHostingServersHash.ContainsKey($zone)) {
LogComment $($zone + " is already there in ZoneAndHostingServersList.");
continue;
}
LogComment $("Searching for servers which are hosting Zone: " + $zone);
$serverList = $null;
foreach($server in $zoneHostingServerList) {
$tempZoneObj = ExecuteCmdLet "Get-DnsServerZone" @{"ComputerName" = $server; "ZoneName" = $zone};
if ($null -ne $tempZoneObj) {
if ($null -eq $serverList) {$serverList = @()};
LogComment $($server + " is hosting Zone: " + $zone);
$serverList += $server;
} else {
if ([RetStatus]::ZoneDoesNotExist -eq $script:cmdLetReturnedStatus) {
LogComment $($server + " doesn't host Zone: " + $zone);
} else {
LogComment $("Failed to get " + $zone + " info on " + $server + " with error " + $script:cmdLetReturnedStatus) `
$script:logLevel.Error;
}
}
}
if ($null -eq $serverList) {
LogComment $("Didn't find any server which is hosting Zone: " + $zone) `
$script:logLevel.Warning;
}
$zoneAndHostingServersHash.Add($zone, $serverList);
}
return $zoneAndHostingServersHash;
}
#
# Gets all the zones across zone hosting servers and prepare a HashTable of zones
# (except auto-created and TrustAnchors zones) and zoneHostingServerList.
#
Function Get-ZonesHostingOnServers
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$zoneHostingServerList
)
$zoneAndHostingServersHash = $null;
foreach($zoneHostingServer in $zoneHostingServerList) {
$tempZoneObj = ExecuteCmdLet "Get-DnsServerZone" @{"ComputerName" = $zoneHostingServer};
if ($null -ne $tempZoneObj) {
foreach ($zone in $tempZoneObj) {
if (($false -eq $zone.IsAutoCreated) -and ("TrustAnchors" -ne $zone.ZoneName)) {
if ($null -eq $zoneAndHostingServersHash) {$zoneAndHostingServersHash = @{}};
LogComment $($zoneHostingServer + " is hosting Zone: " + $zone.ZoneName);
if ($zoneAndHostingServersHash.ContainsKey($zone.ZoneName)) {
$zoneAndHostingServersHash[$zone.ZoneName] += $zoneHostingServer;
} else {
$zoneAndHostingServersHash.Add($zone.ZoneName, @($zoneHostingServer));
}
}
}
} else {
if ([RetStatus]::Success -eq $script:cmdLetReturnedStatus) {
LogComment $($zoneHostingServer + " doesn't host any Zone");
} else {
LogComment $("Failed to get Zone info on " + $zoneHostingServer + " with error " + $script:cmdLetReturnedStatus) `
$script:logLevel.Error;
}
}
}
return $zoneAndHostingServersHash;
}
#
# Returns scope level or server level Dhcpv4 Option List for default Option ID 6
#
Function Get-EnterpriseDhcpv4OptionId
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Array]$dhcpServerList,
$scopeOption = $false,
$OptionId = 6
)
$optionList = @();
foreach ($dhcpServer in $dhcpServerList) {
try {
if ($true -eq $scopeOption) {
$scopeOptions = @();
$scopeList = ExecuteCmdLet "Get-DhcpServerv4Scope" @{"ComputerName" = $dhcpServer};
foreach ($scope in $scopeList) {
try {
$scopeOption = ExecuteCmdLet "Get-DhcpServerv4OptionValue" `
@{"ComputerName" = $dhcpServer; "OptionId" = $OptionId; "ScopeId" = $scope.ScopeId};
$scopeOptions += $scopeOption;
} catch {
LogComment "Failed to get options for the scope $($scope.ScopeId). Continuing...";
}
}
$optionList += $scopeOptions;
} else {
try {
$serverOptions = ExecuteCmdLet "Get-DhcpServerv4OptionValue" `
@{"ComputerName" = $dhcpServer; "OptionId" = $OptionId};
$optionList += $serverOptions;
} catch {
LogComment "Get-DhcpServerv4OptionValue -ComputerName $($dhcpServer) -OptionId $OptionId failed. Continuing...";
}
}
} catch {
LogComment "Get-DhcpServerv4Scope -ComputerName $($dhcpServer) failed" $script:logLevel.Error;
}
}
$optionList = $optionList | ?{-not([String]::IsNullOrEmpty($_))};
if ($null -eq $optionList) {
LogComment $("No DHCPv4 option found across the DHCP servers for ScopeOption = " + $scopeOption + ", returning with NULL option list.") $script:logLevel.Warning;
}
return $optionList;
}
#
# Returns scope level or server level Dhcpv6 Option List for default Option ID 23
#
Function Get-EnterpriseDhcpv6OptionId
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Array]$dhcpServerList,
$scopeOption = $false,
$OptionId = 23
)
$optionList = @();
foreach ($dhcpServer in $dhcpServerList) {
try {
if ($true -eq $scopeOption) {
$scopeOptions = @();
$scopeList = ExecuteCmdLet "Get-DhcpServerv6Scope" @{"ComputerName" = $dhcpServer};
foreach ($scope in $scopeList) {
try {
$scopeOption = ExecuteCmdLet "Get-DhcpServerv6OptionValue" `
@{"ComputerName" = $dhcpServer; "OptionId" = $OptionId; "Prefix" = $scope.Prefix};
$scopeOptions += $scopeOption;
} catch {
LogComment "Failed to get options for the scope $($scope.Prefix). Continuing...";
}
}
$optionList += $scopeOptions;
} else {
try {
$serverOptions = ExecuteCmdLet "Get-DhcpServerv6OptionValue" `
@{"ComputerName" = $dhcpServer; "OptionId" = $OptionId};
$optionList += $serverOptions;
} catch {
LogComment "Get-DhcpServerv6OptionValue -ComputerName $($dhcpServer) -OptionId $OptionId failed. Continuing...";
}
}
} catch {
LogComment $("Get-DhcpServerv6Scope -ComputerName $($dhcpServer) failed") $script:logLevel.Error;
}
}
$optionList = $optionList | ?{-not([String]::IsNullOrEmpty($_))};
if ($null -eq $optionList) {
LogComment $("No DHCPv6 option found across the DHCP servers for ScopeOption = " + $scopeOption + ", returning with NULL option list.") $script:logLevel.Warning;
}
return $optionList;
}
#
# Tests health of input zones across all DNS Servers
# Verifies all the enterprise DNS servers can resolve these zone names.
# If input zones are root zones then validates _msdcs & _ldap infra records
# Performs a Test-DnsServer query for all input zones
#
Function Test-ZoneHealthAcrossAllDnsServers
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$zoneList,
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
$dnsServerList,
[bool]$isRootZone = $false,
[String]$outputReportName = $MyInvocation.MyCommand
)
$statusArray = @();
foreach($zone in $zoneList) {
$status = New-Object PSObject;
$status | Add-Member -memberType NoteProperty -name "ZoneName" -value $zone;
foreach($dnsServer in $dnsServerList) {
try {
$result = [RetStatus]::Success;
$resultStream = $null;
$retVal1 = Test-DnsServerForInputDnsName $zone $dnsServer;
$resultStream = $resultStream + "ResolveDnsName:" + $retVal1 + "`n";
$retVal2 = Test-DnsServerForInputZone $zone $dnsServer $dnsServer;
$resultStream = $resultStream + "TestDnsServer:" + $retVal2 + "`n";
if (!(([RetStatus]::Success -eq $retVal1) -and ([RetStatus]::Success -eq $retVal2))) {
$result = [RetStatus]::Failure;
}
# If it's root zone then validate _msdcs & _ldap infra records
if ($isRootZone) {
$retVal3 = Test-DnsServerForInputDnsName ("_msdcs." + $zone) $dnsServer;
$resultStream = $resultStream + "MsdcsResolveDnsName:" + $retVal3 + "`n";
$retVal4 = Test-DnsServerForInputZone ("_msdcs." + $zone) $dnsServer $dnsServer;
$resultStream = $resultStream + "MsdcsTestDnsServer:" + $retVal4 + "`n";
$retVal5 = Test-DnsServerForInputDnsName ("_ldap._tcp.dc._msdcs." + $zone) $dnsServer "SRV";
$resultStream = $resultStream + "LdapTCPMsdcsResolveDnsName:" + $retVal5 + "`n";
if (!(([RetStatus]::Success -eq $retVal3) -and ([RetStatus]::Success -eq $retVal4) -and ([RetStatus]::Success -eq $retVal5))) {
$result = [RetStatus]::Failure;
}
}
if ([RetStatus]::Success -eq $result) {
LogComment $("Validation of " + $zone + " passed on DNS Server: " + $dnsServer);
LogComment $("Validation of " + $zone + " passed on DNS Server: " + $dnsServer)
$script:logLevel.Host;
} else {
LogComment $("Validation of " + $zone + " failed on DNS Server: " + $dnsServer)
$script:logLevel.Error;
LogComment $("Validation output:" + $resultStream) $script:logLevel.Error;
$result = $resultStream;
}
} catch {
LogComment $("Test-ZoneHealthAcrossAllDnsServers failed for Zone: " + $zone + " on DNSServer: " + $dnsServer + " `n " + $_.Exception) `
$script:logLevel.Error;
$result = [RetStatus]::Failure;
}
$status = Insert-ResultInObject $status $dnsServer $result;
}
$statusArray += $status;
}
Generate-Report $statusArray $outputReportName $script:resultView.Table;
return $statusArray;
}
#
# Tests health of root domain zones - $domain & _msdcs.$domain across all DNS Servers
# Verifies all the enterprise DNS servers can resolve these root domain names.
# Performs a Test-DnsServer query for input root domain zones
#
Function Test-RootDomainHealthAcrossAllDnsServers
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[HashTable]$domainAndHostingServerHash,
$dnsServerList
)
Test-ZoneHealthAcrossAllDnsServers $domainAndHostingServerHash.Keys $dnsServerList $true $MyInvocation.MyCommand
}
#
# Test health of input zones scavenging setting across all the zone hosting servers. This method verifies that:
# Scavenging should be enabled.
# Scavenging shouldn’t be enabled on more than 1 server.
# Refresh & non-refresh interval should be set to default value (168 hours).
# ScavengeServers should be configured.
#
Function Test-ZoneAgingHealth
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[HashTable]$zoneAndHostingServersHash
)
$status = New-Object PSObject;
foreach($zone in $zoneAndHostingServersHash.keys) {
$result = [RetStatus]::Success;
$agingStatus = $false;
$defaultRefreshInterval = [Timespan]::FromHours(168);
foreach($server in $zoneAndHostingServersHash[$zone]) {
try {
$retObj = ExecuteCmdLet "Get-DnsServerZoneAging" @{"ComputerName" = $server; "ZoneName" = $zone};
if ($null -ne $retObj) {
if ($retObj.AgingEnabled) {
LogComment $("Aging is enabled on Server: " + $server + " for Zone: " + $zone);
# In case of non-default values of Refresh & NoRefresh interval and $null ScavengeServers
# we're only giving below 3 warnings, not considering them as a failure case.
if ($defaultRefreshInterval -ne $retObj.RefreshInterval) {
LogComment $("RefreshInterval is set to non-default value: " + $retObj.RefreshInterval) `
$script:logLevel.Warning;
}
if ($defaultRefreshInterval -ne $retObj.NoRefreshInterval) {
LogComment $("NoRefreshInterval is set to non-default value: " + $retObj.NoRefreshInterval) `
$script:logLevel.Warning;
}
if ($null -eq $retObj.ScavengeServers) {
LogComment $("There's no ScavengeServers configured.") $script:logLevel.Warning;
}
# If Aging is enabled on more than 1 server, considering it as failure case.
if ($agingStatus) {
$result = [RetStatus]::Failure;
LogComment $("Aging is enabled on more than one server for Zone: " + $zone) `
$script:logLevel.Warning;
} else {
$agingStatus = $true;
}
} else {
LogComment $("Aging is disabled on Server: " + $server + " for Zone: " + $zone);
}
} else {
if ([RetStatus]::OperationIsNotSupported -eq $script:cmdLetReturnedStatus) {
LogComment $($zone + " is non-primary zone on " + $server);
} else {
LogComment $("Failed to get " + $zone + " aging info on " + $server + " with error " + $script:cmdLetReturnedStatus) `
$script:logLevel.Error;
$result = [RetStatus]::Failure;
}
}
} catch {
LogComment $("Test-ZoneAgingHealth failed for Zone: " + $zone + " on Server: " + $server + " `n " + $_.Exception) `
$script:logLevel.Error;
$result = [RetStatus]::Failure;
}
# If Aging is not enabled on any server, considering it as failure case.
if (!$agingStatus) {
LogComment $("No server found with zone aging enabled for the Zone: " + $zone) `
$script:logLevel.Warning;
$result = [RetStatus]::Failure;
}
if ([RetStatus]::Success -eq $result) {
LogComment $("Zone Aging setting validation of " + $zone + " passed.");
LogComment $("Zone Aging setting validation of " + $zone + " passed.") `
$script:logLevel.Host;
} else {
LogComment $("Zone Aging setting validation of " + $zone + " failed.") `
$script:logLevel.Error;
}
$status = Insert-ResultInObject $status $zone $result;
}
}
Generate-Report $status $MyInvocation.MyCommand $script:resultView.List;
return $status;
}
#
# Tests health of delegation chains inside all the input zones hosted across all servers.
# Verifies name resolution is happening properly through the NameServers pointed by these delegations.
#
Function Test-ZoneDelegationHealth
{
param (
[parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[HashTable]$zoneAndHostingServersHash
)
$statusArray = @();
foreach($zone in $zoneAndHostingServersHash.keys) {
foreach($server in $zoneAndHostingServersHash[$zone]) {
# Get all NS records under the zone.
$rrObj = ExecuteCmdLet "Get-DnsServerResourceRecord" @{"ComputerName" = $server; "RRType" = "NS"; "ZoneName" = $zone};
# Exclude root level NS record.
$rrObj = $rrObj |? hostname -ne "@";
$zoneDelObj = $null;
if ($null -ne $rrObj) {
LogComment $("Performing delegation check for " + $zone + " on " + $server);
foreach($rr in $rrObj) {
$result = [RetStatus]::Success;
$resultStream = $null;
$status = New-Object PSObject;
$status | Add-Member -memberType NoteProperty -name "ZoneName :: Server" -value ($zone + " :: " + $server) -Force;
try {
$zoneDelObj = ExecuteCmdLet "Get-DnsServerZoneDelegation" @{"ComputerName" = $server; "ZoneName" = $zone; "ChildZoneName" = $rr.hostname};
if ($null -eq $zoneDelObj) {
LogComment $("Failed to get info for " + $rr.hostname + " on " + $server + " with error " + $script:cmdLetReturnedStatus) `
$script:logLevel.Error;
if ([RetStatus]::Success -eq $script:cmdLetReturnedStatus) {
$result = [RetStatus]::Failure;
} else {
$result = $script:cmdLetReturnedStatus;
}
} else {
foreach($zoneDel in $zoneDelObj) {
$zoneDelName = $zoneDel.ChildZoneName;
LogComment $("Validating ZoneDelegation: " + $zoneDelName + " at server: " + $server);
[Array]$rr_ip = $zoneDel.IPAddress
foreach ($ipRec in $rr_ip) {
if ($null -ne $ipRec){
$ipAddr = @();
if ($ipRec.RecordType -eq "A") {
$ipAddr = $ipRec.RecordData.IPv4Address
} else {
$ipAddr = $ipRec.RecordData.IPv6Address
}
foreach ($ip in $ipAddr) {
$retVal = Test-DnsServerForInputDnsName $zoneDelName $ip;
$resultStream = $resultStream + $ip.IPAddressToString + ":" + $retVal + "`n";
if ([RetStatus]::Success -eq $retVal) {
LogComment $("Validated NameServer IP: " + $ip + " for ZoneDelegation: " + $zoneDelName + " on Server: " + $server);
LogComment $("Validated NameServer IP: " + $ip + " for ZoneDelegation: " + $zoneDelName + " on Server: " + $server) `
$script:logLevel.Host;
} else {
$result = [RetStatus]::Failure;
LogComment $("Validation of NameServer IP: " + $ip + " for ZoneDelegation: " + $zoneDelName + " on Server: " + $server + " failed.") `
$script:logLevel.Error;
}
}
} else {
$result = [RetStatus]::Failure;
$resultStream = $resultStream + "NullIPAddressRecord;";
LogComment $("IPAddress record is null for ZoneDelegation: " + $zoneDelName + " on Server: " + $server) $script:logLevel.Error;
}
}
}
if ([RetStatus]::Success -ne $result) {
$result = $resultStream;
LogComment $("Validation output:" + $resultStream) $script:logLevel.Error;
}
}
} catch {
LogComment $("Test-ZoneDelegationHealth failed for Zone: " + $zone + " on Server: " + $server + " `n " + $_.Exception) `
$script:logLevel.Error;
$result = [RetStatus]::Failure;
}
$status = Insert-ResultInObject $status $rr.hostname $result;
$statusArray += $status;