0

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?

4 Answers 4

2

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 '-'
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

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

Comments

1

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 ''

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.