Vasyl Stepulo
Vasyl Stepulo

Reputation: 1603

Powershell get particular MAC address in string format

I have an issue with my code - I can grab particular MACadress and convert it into string. Problem, is that in my method, it takes some illegal characters:

$CurrMac = get-netadapter | Where {$_.name -Match "Ethernet 2"}
$CurrMacAddr = $CurrMac.MacAddress
out-string -inputobject $CurrMacAddr -outvariable CurrMac2
$CurrMac2 = $CurrMac2.Substring(0,$CurrMac2.Length-1)

So, my question - is there any other way to extract mac address for adapter with name "Ethernet 2" in string without special characters?

Upvotes: 0

Views: 2032

Answers (4)

user6811411
user6811411

Reputation:

Just another way

  • Pass the Name directly to Get-NetAdapter
  • split the MacAddress at the '-'
  • join the resulting array

(Get-NetAdapter 'Ethernet 2').MacAddress -split '-' -join ''

Upvotes: 1

mklement0
mklement0

Reputation: 437082

To complement the existing, helpful answers with a PowerShell-idiomatic PSv4+ solution based on the .Where() array method, which performs better than use of the Where-Object cmdlet:

PS> (Get-NetAdapter).Where({ $_.Name -match 'Ethernet 2'}).MacAddress -replace '-'
00B0362FF73A  # e.g.

Upvotes: 2

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174435

You don't need Out-String - the MacAddress property is already a string.

If you want to replace the - characters, you could use either String.Replace():

$CurrMacAddr = $CurrMac.MacAddress.Replace('-','')

or the -replace operator:

$CurrMacAddr = $CurrMac.MacAddress -replace '-'

Upvotes: 2

Roger Lipscombe
Roger Lipscombe

Reputation: 91825

$adapter = Get-NetAdapter | Where {$_.Name -Match "Ethernet 2"}
$result = $adapter.MacAddress.Replace("-", "")

Upvotes: 1

Related Questions