It appears that -eq can only compare against a literal. I am trying to compare against a variable like this. This code does not work
> $macaddr = ((getmac /v /fo csv | findstr ASIX) -split "," )[2]
> $echo $macaddr
"00-01-02-03-04-05"
> $adapter = Get-NetAdapter | ? {$_.MacAddress -eq $macaddr}
> echo $adapter
>
If I change the comparison to a literal, it appears to work fine.
> $adapter = Get-NetAdapter | ? {$_.MacAddress -eq "00-01-02-03-04-05"}
> echo $adapter
Name InterfaceDescription ifIndex Status MacAddress LinkSpeed
---- -------------------- ------- ------ ---------- ---------
Ethernet 3 ASIX AX88179 USB 3.0 to Gigabit Ethe... 12 Up 00-01-02-03-04-05 100 Mbps
How should I handle the comparison?
The /fo csv
option makes getmac.exe
quote the mac addresses, so the literal string value is not 00-01-02-03-04-05
, but "00-01-02-03-04-05"
(including the quotation marks), and they're obviously different:
> '00-01-02-03-04-05' -eq '"00-01-02-03-04-05"'
False
Either use ConvertFrom-Json
to re-parse the output:
$macAddr = getmac /v /fo csv |ConvertFrom-Csv |Where-Object 'Network Adapter' -like '*ASIX*' |Select-Object -Expand 'Physical Address'
Or use the Trim()
method to remove the quotation marks from the raw output:
$macaddr = ((getmac /v /fo csv | findstr ASIX) -split "," )[2].Trim('"')