-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers-networking.ps1
More file actions
827 lines (694 loc) · 28.7 KB
/
helpers-networking.ps1
File metadata and controls
827 lines (694 loc) · 28.7 KB
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
##############################################################
#
# A collection of helper functions for Networking
#
##############################################################
function Test-IpReachability {
<#
.SYNOPSIS
Probe point-in-time ICMP reachability for one or more IP targets.
.DESCRIPTION
Sends one or more ICMP echo attempts to each target and returns one output
object per unique target IP.
When a ping attempt cannot be performed due to an internal runtime error,
the target result's lastStatus is set to a string beginning with
"PROGRAM EXCEPTION:".
.OUTPUTS
[pscustomobject]
One object per unique target IP with properties:
- ip (string): The target IP string as provided/normalized.
- responded (bool): $true if any attempt succeeded; otherwise $false.
- attempts (int): Number of attempts made for that target.
- respondedOnAttempt (Nullable[int]): Attempt number of first success;
otherwise $null.
- rttMs (Nullable[long]): Round-trip time in milliseconds for the
successful response; otherwise $null.
- lastStatus (string): Final status observed for the target. For runtime
errors, begins with "PROGRAM EXCEPTION:".
.PARAMETER Ip
One or more target IPs to probe.
Accepts:
- A single value convertible to string.
- An enumerable of values convertible to string.
- A single string containing multiple targets separated by commas and/or
whitespace.
.PARAMETER Retry
Number of additional attempts per target after the first attempt.
.PARAMETER TimeoutMs
Timeout in milliseconds for each attempt.
.EXAMPLE
Test-IpReachability -Ip '10.1.11.50,10.1.11.55 10.1.11.56' `
-Retry 1 -TimeoutMs 500 -Verbose
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0)][Alias('Ips')][object]$Ip,
[ValidateRange(1,1000)][int]$Retry=1,
[ValidateRange(1,60000)][int]$TimeoutMs=500
)
$ips=@()
if($Ip -is [string]){
$s=$Ip.Trim()
if($s -match '[,\s]'){ $ips=@($s -split '[,\s]+' | Where-Object { $_ -and $_.Trim() } | ForEach-Object { $_.Trim() }) }
else { $ips=@($s) }
} elseif($Ip -is [System.Collections.IEnumerable]){
foreach($x in $Ip){ if($x -ne $null -and "$x".Trim()){ $ips += "$x".Trim() } }
} else { $ips=@("$Ip".Trim()) }
if($ips.Count -eq 0){ return @() }
$ips=@($ips | Select-Object -Unique)
$state=@{}
foreach($a in $ips){
$state[$a]=[pscustomobject]@{ip=$a;responded=$false;attempts=0;respondedOnAttempt=$null;rttMs=$null;lastStatus=$null}
}
$retryableStatuses = New-Object 'System.Collections.Generic.HashSet[string]'
$null = $retryableStatuses.Add('TimedOut')
$null = $retryableStatuses.Add('Unknown')
$terminalStatuses = New-Object 'System.Collections.Generic.HashSet[string]'
@(
'DestinationHostUnreachable','DestinationNetworkUnreachable','DestinationUnreachable',
'DestinationProhibited','DestinationProtocolUnreachable','DestinationPortUnreachable',
'BadRoute','BadDestination','DestinationScopeMismatch','PacketTooBig',
'ParameterProblem','BadOption','BadHeader','UnrecognizedNextHeader',
'TtlExpired','TimeExceeded','TtlReassemblyTimeExceeded'
) | ForEach-Object { $null = $terminalStatuses.Add($_) }
$maxAttempts = 1 + $Retry
$pending = New-Object System.Collections.ArrayList
$null=$pending.AddRange($ips)
for($attempt=1; $attempt -le $maxAttempts -and $pending.Count -gt 0; $attempt++){
$batch=@()
foreach($a in @($pending)){
$st=$state[$a]
if($st.responded){ continue }
$st.attempts++
$p=New-Object System.Net.NetworkInformation.Ping
$t=$null
try{
$t=$p.SendPingAsync($a,$TimeoutMs)
} catch {
$st.lastStatus="PROGRAM EXCEPTION: $($_.Exception.Message)"
Write-Verbose "attempt=$attempt/$maxAttempts ip=$a status='$($st.lastStatus)' retry=no (program exception)"
try{ $p.Dispose() } catch {}
continue
}
$batch += [pscustomobject]@{ip=$a;ping=$p;task=$t}
}
$tasks=@($batch | ForEach-Object { $_.task })
if($tasks.Count -gt 0){
try{
[System.Threading.Tasks.Task]::WaitAll([System.Threading.Tasks.Task[]]$tasks)
} catch {
Write-Warning "WaitAll exception: $($_.Exception.GetType().FullName): $($_.Exception.Message)"
}
}
$newPending = New-Object System.Collections.ArrayList
foreach($b in $batch){
$a=$b.ip; $st=$state[$a]
$statusName=$null
$note=$null
try{
if($b.task.IsFaulted){
$msg=$b.task.Exception.InnerException.Message
$st.lastStatus="PROGRAM EXCEPTION: $msg"
$statusName=$st.lastStatus
} elseif($b.task.Status -eq [System.Threading.Tasks.TaskStatus]::RanToCompletion){
$r=$b.task.Result
$statusName=$r.Status.ToString()
$st.lastStatus=$statusName
if($r.Status -eq [System.Net.NetworkInformation.IPStatus]::Success){
$st.responded=$true
$st.rttMs=$r.RoundtripTime
$st.respondedOnAttempt=$attempt
}
} else {
$statusName=$b.task.Status.ToString()
$st.lastStatus=$statusName
}
} catch {
$st.lastStatus="PROGRAM EXCEPTION: $($_.Exception.Message)"
$statusName=$st.lastStatus
} finally {
try{ $b.ping.Dispose() } catch {}
}
$willRetry=$false
if(-not $st.responded -and $attempt -lt $maxAttempts){
$ls="$($st.lastStatus)"
if($retryableStatuses.Contains($ls)){ $willRetry=$true }
}
if($st.responded){
Write-Verbose "attempt=$attempt/$maxAttempts ip=$a status='$statusName' rttMs=$($st.rttMs) retry=no (success)"
} else {
$why="no"
if($attempt -ge $maxAttempts){ $why="no (attempt limit reached)" }
elseif($terminalStatuses.Contains("$($st.lastStatus)")){ $why="no (terminal status)" }
elseif($st.lastStatus -like 'PROGRAM EXCEPTION:*'){ $why="no (program exception)" }
elseif($willRetry){ $why="yes (retryable status)" }
else { $why="no (non-retryable status)" }
Write-Verbose "attempt=$attempt/$maxAttempts ip=$a status='$statusName' retry=$why"
}
if($willRetry){
$null=$newPending.Add($a)
}
}
$pending.Clear() | Out-Null
if($newPending.Count -gt 0){ $null=$pending.AddRange(@($newPending | Select-Object -Unique)) }
}
$out = foreach($a in $ips){ $state[$a] }
$out | Select-Object ip,responded,attempts,respondedOnAttempt,rttMs,lastStatus
}
function Test-TcpPort {
<#
.SYNOPSIS
Quickly tests whether a TCP connection can be established.
.DESCRIPTION
Tests TCP connectivity from the current machine to the specified target
and ports, and returns one result object per requested port.
The target MAY be specified as an IP address or a hostname. If name
resolution fails, the function throws a terminating error.
Ports are accepted in multiple input forms.
The -TimeoutMs value is a single overall time budget (in milliseconds) for
the entire batch of ports, not a per-port timeout.
.OUTPUTS
System.Management.Automation.PSCustomObject
One object per normalized port, with these properties:
- port (int) The TCP port tested.
- open (bool) $true if a connection was established; otherwise $false.
- detail (string) "connected" on success; otherwise an error identifier
or "timeout" if the overall time budget was reached.
Objects are emitted in ascending port order.
.PARAMETER Target
Target host to test.
.PARAMETER Ports
Ports to test. Accepts:
- a single integer
- an array of integers
- a string containing one or more port numbers
- an enumerable of values convertible to integers
.PARAMETER TimeoutMs
Overall time budget for the entire batch, in milliseconds. Defaults to
200. When the budget is exhausted, remaining ports are reported as
"timeout".
.EXAMPLE
Test-TcpPort -Target '10.1.11.1' -Ports 80,443,4444
.EXAMPLE
Test-TcpPort -Target 'timesheet-gr.forvismazars.com' -Ports '80,443,4444' `
-TimeoutMs 1000
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0)][string]$Target,
[Parameter(Mandatory=$true,Position=1)][object]$Ports,
[int]$TimeoutMs=200
)
$target=$Target.Trim()
$ipObj=$null
if([System.Net.IPAddress]::TryParse($target,[ref]$ipObj)){
$ipString=$ipObj.IPAddressToString
} else {
try{ $addrs=[System.Net.Dns]::GetHostAddresses($target) } catch { throw "Failed to resolve '$target': $($_.Exception.Message)" }
if(-not $addrs -or $addrs.Count -eq 0){ throw "Failed to resolve '$target' (no addresses returned)" }
$pick=($addrs | Where-Object { $_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork } | Select-Object -First 1)
if(-not $pick){ $pick=$addrs | Select-Object -First 1 }
$ipString=$pick.IPAddressToString
}
$portsList=@()
if($Ports -is [int]){ $portsList=@($Ports) }
elseif($Ports -is [int[]]){ $portsList=$Ports }
elseif($Ports -is [string]){
foreach($tok in ($Ports -split '[^\d]+')){ if($tok -match '^\d+$'){ $portsList += [int]$tok } }
}
elseif($Ports -is [System.Collections.IEnumerable]){
foreach($p in $Ports){ if($p -ne $null -and "$p" -match '^\d+$'){ $portsList += [int]$p } }
} else {
if("$Ports" -match '^\d+$'){ $portsList=@([int]$Ports) }
}
$portsList=@($portsList | Where-Object { $_ -ge 1 -and $_ -le 65535 } | Sort-Object -Unique)
if($portsList.Count -eq 0){ return @() }
$items=@()
foreach($port in $portsList){
$c=New-Object System.Net.Sockets.TcpClient
$iar=$c.BeginConnect($ipString,$port,$null,$null)
$items += [pscustomobject]@{Port=$port;Client=$c;IAR=$iar;Handle=$iar.AsyncWaitHandle}
}
$deadline=(Get-Date).AddMilliseconds($TimeoutMs)
$results=@{}
$pending=New-Object System.Collections.ArrayList
$null=$pending.AddRange($items)
while($pending.Count -gt 0){
$remaining=[int]([Math]::Max(0, ($deadline-(Get-Date)).TotalMilliseconds))
if($remaining -le 0){ break }
$harvested=$false
for($i=$pending.Count-1; $i -ge 0; $i--){
$it=$pending[$i]
if($it.Handle.WaitOne(0,$false)){
$open=$false; $detail="error"
try{
try{
$it.Client.EndConnect($it.IAR)
$open=$true; $detail="connected"
} catch {
$e=$_.Exception
if($e -is [System.Net.Sockets.SocketException]){
$detail=$e.SocketErrorCode.ToString()
} else {
$detail=$e.GetType().FullName
}
}
} catch {
$detail=$_.Exception.GetType().FullName
}
$results[$it.Port]=[pscustomobject]@{port=$it.Port;open=$open;detail=$detail}
try{ $it.Handle.Close() } catch {}
try{ $it.Client.Close() } catch {}
$pending.RemoveAt($i) | Out-Null
$harvested=$true
}
}
if(-not $harvested){
Start-Sleep -Milliseconds ([Math]::Min(10,$remaining))
}
}
foreach($it in @($pending)){
$results[$it.Port]=[pscustomobject]@{port=$it.Port;open=$false;detail="timeout"}
try{ $it.Handle.Close() } catch {}
try{ $it.Client.Close() } catch {}
}
foreach($p in $portsList){ $results[$p] }
}
function Test-NetConnectivityToHost {
<#
Test-NetConnectivityToHost validates that basic network reachability to a target host matches an explicit expectation profile.
What it checks
- ICMP echo (ping): verifies whether the host responds to pings or not.
- TCP ports (optional):
- OpenPorts: ports that are expected to accept a TCP connection.
- ClosedPorts: ports that are expected to refuse or time out (treated as CLOSED/FILTERED).
Output / side effects
- Outputs discrepancies using Write-Warning "[<level>] <message>" (<level> can be pass or failure).
- If -ReturnTrueFalse is used, the function returns $true/$false and emits no warnings.
Notes / interpretation
- A TCP port is considered OPEN only if a TCP connect completes successfully within the timeout window.
- A TCP port is considered CLOSED/FILTERED if the connect fails or does not complete within the timeout.
- If OpenPorts/ClosedPorts are omitted, only the ping expectation is validated.
- If -SkipPing is used, only port expectations are validated.
Example
Test-NetConnectivityToHost -TargetHost 10.30.0.2 -RespondsToPing:$true -OpenPorts @(53,88,135,389,445) -ClosedPorts @(22,3389) -PortTimeoutMs 1000
Example (ports only)
Test-NetConnectivityToHost -TargetHost 10.30.0.2 -SkipPing -OpenPorts @(443) -PortTimeoutMs 1000
Example (boolean result only)
Test-NetConnectivityToHost -TargetHost 10.30.0.2 -RespondsToPing:$true -ReturnTrueFalse
#>
[CmdletBinding(DefaultParameterSetName='Ping')]
param(
[Parameter(Mandatory=$true)]
[Alias('Host')]
[string]$TargetHost,
[Parameter(Mandatory=$true, ParameterSetName='Ping')]
[bool]$RespondsToPing,
[int[]]$OpenPorts,
[int[]]$ClosedPorts,
[Parameter(Mandatory=$true, ParameterSetName='PortsOnly')]
[switch]$SkipPing,
[int]$PortTimeoutMs = 1000,
[switch]$ReturnTrueFalse
)
$LogPass = {
param($m)
if(-not $ReturnTrueFalse){ Write-Warning "[pass] $m" }
}
$LogFailure = {
param($m)
if(-not $ReturnTrueFalse){ Write-Warning "[failure] $m" }
}
$ok=$true
$openExpected=@(); if($OpenPorts){ $openExpected=@($OpenPorts | ForEach-Object { [int]$_ } | Sort-Object -Unique) }
$closedExpected=@(); if($ClosedPorts){ $closedExpected=@($ClosedPorts | ForEach-Object { [int]$_ } | Sort-Object -Unique) }
$overlap=@($openExpected | Where-Object { $closedExpected -contains $_ })
if($overlap.Count -gt 0){
throw ("Invalid arguments: port(s) specified as both OPEN and CLOSED: {0}" -f (($overlap | Sort-Object -Unique) -join ', '))
}
$targetName = $TargetHost.Trim()
$TargetIp = $null
$isIPv4 = ($targetName -match '^\d{1,3}(\.\d{1,3}){3}$')
$isIPv6 = ($targetName -match '^([0-9A-Fa-f]{0,4}:){2,7}[0-9A-Fa-f]{0,4}$' -or $targetName -match '^::1$')
if($isIPv4 -or $isIPv6){
$TargetIp = $targetName
} else {
try {
if(Get-Command Resolve-DnsName -ErrorAction SilentlyContinue){
$TargetIp = Resolve-DnsName -Name $targetName -Type A -ErrorAction Stop | Select-Object -ExpandProperty IPAddress -First 1
} else {
$TargetIp = ([System.Net.Dns]::GetHostAddresses($targetName) | Select-Object -First 1).IPAddressToString
}
} catch {
$ok=$false
& $LogFailure "Failed to resolve $($TargetHost): $($_.Exception.Message)"
}
if(-not $TargetIp){
& $LogFailure "Failed to resolve $TargetHost"
if($ReturnTrueFalse){ return $false }
return
}
}
$allPorts=@()
if($openExpected){ $allPorts += $openExpected }
if($closedExpected){ $allPorts += $closedExpected }
$portState=@{}
if($allPorts.Count -gt 0){
try{
foreach($r in @(Test-TcpPort -Target $TargetIp -Ports $allPorts -TimeoutMs $PortTimeoutMs)){
if($null -ne $r -and $null -ne $r.Port){
$portState[[int]$r.Port] = [bool]$r.Open
}
}
} catch {
& $LogFailure ("TCP probe failed for host {0}: {1}" -f $TargetHost, $_.Exception.Message)
$ok=$false
}
}
if($PSCmdlet.ParameterSetName -eq 'Ping'){
$pingActual=$false
$pingObj=$null
$pingTask=$null
try { $pingObj = New-Object System.Net.NetworkInformation.Ping } catch {}
try { if($pingObj){ $pingTask = $pingObj.SendPingAsync($TargetIp,$PortTimeoutMs) } } catch {}
if($pingTask){
try{
if(-not $pingTask.IsCompleted){ $null = $pingTask.Wait($PortTimeoutMs) }
if($pingTask.IsCompleted -and -not $pingTask.IsFaulted -and $pingTask.Result){
$pingActual = ($pingTask.Result.Status -eq [System.Net.NetworkInformation.IPStatus]::Success)
}
} catch {
$pingActual=$false
}
}
try { if($pingObj){ $pingObj.Dispose() } } catch {}
if($RespondsToPing -and -not $pingActual){
& $LogFailure "Host $TargetHost was expected to respond to ping, but does not"
$ok=$false
}
if((-not $RespondsToPing) -and $pingActual){
& $LogFailure "Host $TargetHost was expected to NOT respond to ping, but it does"
$ok=$false
}
}
foreach($p in $openExpected){
$isOpen=$false
if($portState.ContainsKey($p)){ $isOpen = [bool]$portState[$p] }
if(-not $isOpen){
& $LogFailure "Port $($TargetHost):$p was expected to be OPEN, but is not"
$ok=$false
}
}
foreach($p in $closedExpected){
$isOpen=$false
if($portState.ContainsKey($p)){ $isOpen = [bool]$portState[$p] }
if($isOpen){
& $LogFailure "Port $($TargetHost):$p was expected to be CLOSED/FILTERED, but is not"
$ok=$false
}
}
if($ReturnTrueFalse){
return $ok
}
if($ok){
& $LogPass "Connectivity to $TargetHost is as expected"
}
}
function Split-IpByReachability {
<#
.SYNOPSIS
Splits input IPs into Alive vs NotAlive based on whether they respond to pings
.DESCRIPTION
Runs Test-IpReachability for the provided targets and returns a single object
containing two string arrays:
- AliveIps: IPs that responded ($true)
- DeadIps: IPs that did not respond ($false) or hit errors/timeouts
.INPUTS
Same accepted shapes as Test-IpReachability -Ip.
.OUTPUTS
[pscustomobject] with:
- AliveIps ([string[]])
- DeadIps ([string[]])
- Results ([pscustomobject[]]) raw per-IP results (handy for lastStatus/rtt)
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0)][Alias('Ips')][object]$Ip,
[ValidateRange(1,1000)][int]$Retry=1,
[ValidateRange(1,60000)][int]$TimeoutMs=500
)
$results = @(Test-IpReachability -Ip $Ip -Retry $Retry -TimeoutMs $TimeoutMs)
$alive = @($results | Where-Object { $_.responded } | Select-Object -ExpandProperty ip)
$dead = @($results | Where-Object { -not $_.responded } | Select-Object -ExpandProperty ip)
[pscustomobject]@{
AliveIps = $alive
DeadIps = $dead
Results = $results
}
}
function Test-NetConnectivityToNetwork {
<#
.SYNOPSIS
Assesses reachability of a network by pinging a list of hosts that are known to reply.
.DESCRIPTION
Given a human-friendly network description (e.g. "10.11.x.y/16") and a list of
IP addresses that are expected to respond to ICMP, this function probes them
(using Split-IpByReachability) and outputs the results using:
Write-Warning "[<level>] ..."
(<level> is one of pass, notice, failure)
If -ReturnListOfAliveHosts is used, the function does not emit warnings and
instead returns the list of responsive hosts.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true,Position=0)][string]$NetworkDescription,
[Parameter(Mandatory=$true,Position=1)][object]$KnownHostIps,
[ValidateRange(1,1000)][int]$Retry=1,
[ValidateRange(1,60000)][int]$TimeoutMs=500,
[switch]$ReturnListOfAliveHosts
)
$ips=@()
if($KnownHostIps -is [string]){
$s=$KnownHostIps.Trim()
if($s -match '[,\s]'){ $ips=@($s -split '[,\s]+' | Where-Object { $_ -and $_.Trim() } | ForEach-Object { $_.Trim() }) }
else { $ips=@($s) }
} elseif($KnownHostIps -is [System.Collections.IEnumerable]){
foreach($x in $KnownHostIps){ if($x -ne $null -and "$x".Trim()){ $ips += "$x".Trim() } }
} else { $ips=@("$KnownHostIps".Trim()) }
$ips=@($ips | Where-Object { $_ } | Select-Object -Unique)
$progress_msg="Pinging $($ips.Count) hosts"
Write-Progress -Activity $progress_msg -Status "Please wait"
$split = Split-IpByReachability -Ip $ips -Retry $Retry -TimeoutMs $TimeoutMs
Write-Progress -Activity $progress_msg -Completed
$alive=@($split.AliveIps)
$dead=@($split.DeadIps)
if($ReturnListOfAliveHosts){
return $alive
}
if(-not $alive -or $alive.Count -eq 0){
$message = "The $NetworkDescription network may be UNRECHABLE because none of the hosts replied to pings"
$comment = "List of hosts that didn't reply: ($($ips -join ', ')); Maybe some VPN connection is down"
Write-Warning "[failure] $message`n$comment"
} elseif($dead -and $dead.Count -gt 0){
$message = "The $NetworkDescription network is reachable (at least one host replied to pings)"
Write-Warning "[pass] $message"
$message = "Note that some hosts of $NetworkDescription did not reply to pings (that's often normal)"
$comment = "List of hosts that didn't reply: ($($dead -join ', '))`nIf some hosts are consistently failing, consider if you should update the list of hosts you ping"
Write-Warning "[notice] $message`n$comment"
} else {
$message = "The $NetworkDescription network is reachable; all known hosts replied to pings"
$comment = "List of hosts that replied: ($($ips -join ', '))"
Write-Warning "[pass] $message`n$comment"
}
}
function Test-ShareLikelyUp {
<#
.SYNOPSIS
QUICKLY tests whether the host of a UNC share is LIKELY reachable over SMB.
.DESCRIPTION
This is a FAST reachability test, not a definitive share-access test. A positive result means the host likely has SMB available. It does not prove that the share exists or that the current user has access to it.
Optionally verifies that at least one configured DNS server falls within an expected CIDR range (prefer to pass it so that you don't spend time on failed DNS resolutions), resolves the host to IPv4 and/or IPv6 addresses, and tests whether any resolved address accepts a TCP connection on port 445 within a short timeout. Supports hostnames, IPv4 UNC hosts, and Windows IPv6-literal UNC hosts.
.PARAMETER SharePath
UNC share path whose host will be tested.
.PARAMETER DnsCidrs
Optional CIDR ranges. When specified, at least one configured DNS server must fall within one of these ranges or the test returns a negative result.
.PARAMETER TcpTimeoutMs
For the connection test to TCP port 445 (SMB).
.OUTPUTS
A PSCustomObject with the test outcome and discovered details.
.EXAMPLE
Test-ShareLikelyUp -SharePath '\\server01\share'
.EXAMPLE
Test-ShareLikelyUp -SharePath '\\192.168.1.2\foo'
.EXAMPLE
Test-ShareLikelyUp -SharePath '\\server01.contoso.local\share' -DnsCidrs '10.30.0.0/16'
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$SharePath,
[string[]]$DnsCidrs,
[int]$TcpTimeoutMs = 400
)
function Convert-IpAddressToBigInteger {
param([Parameter(Mandatory)][System.Net.IPAddress]$IpAddress)
$bytes = $IpAddress.GetAddressBytes()
[Array]::Reverse($bytes)
$unsignedBytes = New-Object byte[] ($bytes.Length + 1)
[Array]::Copy($bytes, 0, $unsignedBytes, 0, $bytes.Length)
[System.Numerics.BigInteger]::new($unsignedBytes)
}
function Test-IpInCidr {
param(
[Parameter(Mandatory)][string]$IpAddress,
[Parameter(Mandatory)][string]$Cidr
)
$parts = $Cidr -split '/'
if ($parts.Count -ne 2) {
throw "Invalid CIDR: $Cidr"
}
$networkIp = [System.Net.IPAddress]::Parse($parts[0])
$candidateIp = [System.Net.IPAddress]::Parse($IpAddress)
$prefixLength = [int]$parts[1]
if ($networkIp.AddressFamily -ne $candidateIp.AddressFamily) {
return $false
}
if ($candidateIp.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) {
if ($prefixLength -lt 0 -or $prefixLength -gt 32) {
throw "Invalid IPv4 CIDR prefix length in $Cidr"
}
} elseif ($candidateIp.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
if ($prefixLength -lt 0 -or $prefixLength -gt 128) {
throw "Invalid IPv6 CIDR prefix length in $Cidr"
}
} else {
throw "Unsupported address family in $Cidr"
}
$candidateValue = Convert-IpAddressToBigInteger -IpAddress $candidateIp
$networkValue = Convert-IpAddressToBigInteger -IpAddress $networkIp
$bitCount = if ($candidateIp.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) { 32 } else { 128 }
if ($prefixLength -eq 0) {
return $true
}
$hostBits = $bitCount - $prefixLength
$candidatePrefix = $candidateValue -shr $hostBits
$networkPrefix = $networkValue -shr $hostBits
($candidatePrefix -eq $networkPrefix)
}
function Test-Tcp445Open {
param(
[Parameter(Mandatory)][string]$ComputerName,
[Parameter(Mandatory)][int]$TimeoutMs
)
$client = New-Object System.Net.Sockets.TcpClient
try {
$async = $client.BeginConnect($ComputerName, 445, $null, $null)
if (-not $async.AsyncWaitHandle.WaitOne($TimeoutMs, $false)) {
return $false
}
$null = $client.EndConnect($async)
return $true
} catch {
return $false
} finally {
$client.Close()
}
}
function ConvertFrom-Ipv6LiteralHost {
param([Parameter(Mandatory)][string]$HostName)
if ($HostName -notmatch '\.ipv6-literal\.net$') {
return $null
}
$base = $HostName -replace '\.ipv6-literal\.net$', ''
$ipv6 = $base.Replace('-', ':')
try {
$parsed = [System.Net.IPAddress]::Parse($ipv6)
if ($parsed.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6) {
return $parsed.IPAddressToString
}
return $null
} catch {
return $null
}
}
function Test-IsIpAddress {
param([Parameter(Mandatory)][string]$Text)
try {
$null = [System.Net.IPAddress]::Parse($Text)
return $true
} catch {
return $false
}
}
$result = [pscustomobject]@{
MatchingDnsServers = @()
ResolvedAddresses = @()
ReachableAddress = $null
LikelyUp = $false
FailureReason = $null
}
if ($SharePath -notmatch '^[\\]{2}([^\\]+)\\') {
$result.FailureReason = "SharePath is not a valid UNC path."
return $result
}
$targetHost = $Matches[1]
if ($DnsCidrs -and $DnsCidrs.Count -gt 0) {
$dnsServers = @()
try {
$dnsServers = @(Get-DnsClientServerAddress -ErrorAction Stop |
ForEach-Object { $_.ServerAddresses } |
Where-Object { $_ } |
Select-Object -Unique)
} catch {
$result.FailureReason = "Failed to read client DNS server configuration."
return $result
}
foreach ($dnsServer in $dnsServers) {
foreach ($cidr in $DnsCidrs) {
try {
if (Test-IpInCidr -IpAddress $dnsServer -Cidr $cidr) {
$result.MatchingDnsServers += $dnsServer
break
}
} catch {
}
}
}
$result.MatchingDnsServers = @($result.MatchingDnsServers | Select-Object -Unique)
if ($result.MatchingDnsServers.Count -eq 0) {
$result.FailureReason = "No configured DNS server matched the expected network list."
return $result
}
}
$ipv6LiteralAddress = ConvertFrom-Ipv6LiteralHost -HostName $targetHost
if ($ipv6LiteralAddress) {
$result.ResolvedAddresses = @($ipv6LiteralAddress)
} elseif (Test-IsIpAddress -Text $targetHost) {
$result.ResolvedAddresses = @(([System.Net.IPAddress]::Parse($targetHost)).IPAddressToString)
} else {
try {
$result.ResolvedAddresses = @([System.Net.Dns]::GetHostAddresses($targetHost) |
Where-Object {
$_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork -or
$_.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetworkV6
} |
Select-Object -ExpandProperty IPAddressToString -Unique)
} catch {
$result.FailureReason = "DNS resolution failed."
return $result
}
if ($result.ResolvedAddresses.Count -eq 0) {
$result.FailureReason = "DNS resolution returned no IP addresses."
return $result
}
}
foreach ($address in $result.ResolvedAddresses) {
if (Test-Tcp445Open -ComputerName $address -TimeoutMs $TcpTimeoutMs) {
$result.ReachableAddress = $address
$result.LikelyUp = $true
return $result
}
}
$result.FailureReason = "No reachable TCP 445 endpoint was found."
return $result
}