-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-GatewayIp.ps1
More file actions
46 lines (39 loc) · 1.5 KB
/
Get-GatewayIp.ps1
File metadata and controls
46 lines (39 loc) · 1.5 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
function Get-GatewayIp {
[CmdletBinding()]
param()
begin {
Write-Verbose -Message ((Get-ResStr 'STARTING_FUNCTION') -f $myInvocation.Mycommand)
New-Variable -Name 'result' -Scope 'Private' -Value ([string]'')
$initialVariables = Get-CurrentVariables -Debug:$DebugPreference
}
process {
try {
<#
# Not working in some LTE networks 2023-07-14
$result= (Get-NetRoute -DestinationPrefix '0.0.0.0/0' `
-ErrorAction SilentlyContinue | `
Sort-Object -Property RouteMetric | `
Select-Object -First 1).NextHop
#>
$netRoutes = Get-NetRoute -DestinationPrefix '0.0.0.0/0' | Sort-Object -Property RouteMetric
$routePrint = route print
$matchingRoutes = @()
# For each route in $netRoutes, check if it exists in $routePrint
foreach ($route in $netRoutes) {
if ($routePrint -match $route.NextHop) {
$matchingRoutes += $route
}
}
# Sort the matching routes by their RouteMetric and select the first one
$result = ($matchingRoutes | Sort-Object -Property RouteMetric | Select-Object -First 1).NextHop
}
catch {
$result='0.0.0.0'
}
}
end {
Get-CurrentVariables -InitialVariables $initialVariables -Debug:$DebugPreference
Return $result
}
# Test: Get-GatewayIp
}