简体   繁体   中英

Get-WmiObject Win32_NetworkAdapterConfiguration -Match failing

So I am using this:

$IPA = (Get-NetIPAddress | Where-Object InterfaceAlias -eq "MyPortName").IPv4Address

and then I want to use the following to grab the Subnet Mask for that IP:

$IPInfo = (Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object IPAddress -Match $IPA)

Followed by:

$SubMask = $IPInfo.IPSubnet[0]

But this fails with $IPInfo being blank. If I hard code the IPAddress it works:

$IPInfo = (Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object IPAddress -Match 10.45.22.100)

But the port IP will always be different. Why is it not taking the $IPA as a match parameter?

EDIT: The IP Address being reported has both the IPv4 and IPv6 which is why I am trying to do -Match against the IPv4.

As we have discovered in comments you are getting an array returned for your $IPA . It looks fine in console as PowerShell unrolls the array to display all elements. Since there is only one it was misleading.

((Get-NetIPAddress | Where-Object InterfaceAlias -eq "Local Area Connection").IPv4Address).gettype().fullname
System.Object[]

Likely it was trying to match "System.Object[]" which is why you did not get the result you wanted.

Few ways around this. A simple one would be to always return the -First result in your query.

(Get-NetIPAddress | Where-Object InterfaceAlias -eq "Local Area Connection").IPv4Address | select -first 1).gettype().fullname

So just use | select -first 1 | select -first 1 and you should get the results you expect.


I caution the use of -match here. Understand that -match and -replace support regex pattern strings. So if you have regex meta characters in your strings you can get unexpected results.

This happens because $IPA is really an array of objects. When you run Get-NetIPAddress | Where-Object InterfaceAlias -eq "MyPortName" Get-NetIPAddress | Where-Object InterfaceAlias -eq "MyPortName" it returns an array of CIM instances of type MSFT_NetIPAddress. When you ask for IPv4Address member by running $IPA = (Get-NetIPAddress | Where-Object InterfaceAlias -eq "MyPortName").IPv4Address the array is still there but the elements of the array that don't have IPv4Address are not shown. Take a look at the following example.

$NetIPAddresses = (Get-NetIPAddress | where {$_.InterfaceAlias -eq "Ethernet" -and $_.AddressFamily -eq "IPv4"})
foreach ($NetIPAddress in $NetIPAddresses) {
   $IPA = $NetIPAddress.IPv4Address
   $IPInfo = (Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object IPAddress -Match $IPA)
   $IPInfo.IPSubnet[0]
}

This will show subnet mask for each IPv4 address on the given interface.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM