$e = $ErrorActionPreference
$ErrorActionPreference="stop"
$E_Subnet_1 = '10.0.1'
$E_Subnet_2 = '10.0.2'
$O_Subnet_1 = '10.11.1'
$O_Subnet_2 = '10.11.2'
$D_Subnet_1 = '10.12.1'
$D_Subnet_2 = '10.12.2'
$Ethernet0 = 'Ethernet0'
$All_Subnets = @("$E_Subnet_1", "$E_Subnet_2", "$O_Subnet_1",
"$O_Subnet_2", "$D_Subnet_1", "$D_Subnet_2")
$result = (Get-NetAdapter |
? status -eq 'up' |
Get-NetIPAddress -ErrorAction 0 |
? PrefixOrigin -eq 'Manual' |
? IPAddress -match $All_Subnets |
foreach { $Ethernet0 -eq $_.InterfaceAlias})
Write-Host "interface_alias=$result"
If you will please consider the PowerShell snippet above which queries the network interfaces and based on the matching subnet it then checks if the interface name equals "Ethernet0" producing a boolean value.
The IPAddress of the server I am currently working matches the first three octets of $D_Subnet_1 and produces a value of interface_alias=True if I target $D_Subnet_1 like this:
$result = (Get-NetAdapter |
? status -eq 'up' |
Get-NetIPAddress -ErrorAction 0 |
? PrefixOrigin -eq 'Manual' |
? IPAddress -match $D_Subnet_1 |
foreach { $Ethernet0 -eq $_.InterfaceAlias})
Write-Host "interface_alias=$result"
But if I try to run the command using the $All_Subnets array:
$result = (Get-NetAdapter |
? status -eq 'up' |
Get-NetIPAddress -ErrorAction 0 |
? PrefixOrigin -eq 'Manual' |
? IPAddress -match $All_Subnets |
foreach { $Ethernet0 -eq $_.InterfaceAlias})
Write-Host "interface_alias=$result"
It just produces interface_alias= with no value at all.
I have tried swapping -match for -contain and like with no luck. How can I fix this?
You're using the wrong comparisons here:
Where-Object -Property 'IPAddress' -Match @('10.30.2','10.40.2')
You need to grab the first 3 octets to do this comparison properly:
Where-Object -FilterScript { $_.IPAddress.Substring(0, $_.IPAddress.LastIndexOf('.')) -in $All_Subnets }
And if you're not on version 3+, just swap the comparison's sides and change the operator to -contains
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With