Retrieve Remote MAC Address in PowerShell

Shay Levi played off my mac address retreival code yesterday and shared his own PowerShell script to retrieve a mac address.  Here's another PowerShell script to retrieve a mac address using get-snmp from NetCmdlets:

## Retrieves the MAC address of an snmp-enabled device 
## Returns a hex string that is the MAC address

##

## usage: get-mac [-agent] <string>
##


param( [string] $agent = "10.0.1.11" )

#a function to convert an octetstring into a hex string
function get-hex($octectstring) {
$len = $octectstring.length
$hex = @()
for
($j=0;$j -lt $len;$j++)
{
$b = "{0:X}" -f ([int]$octectstring[$j])
$hex = $hex + $b
}
return $hex
}

#get the number of network interfaces on the agent device:
$numifs = (get-snmp -agent $agent -oid 1.3.6.1.2.1.2.1.0).OIDValue

#for each interface, get the mac address:

for($i=1;$i -le $numifs; $i++)
{
$str = (get-snmp -agent 10.0.1.11 -oid 1.3.6.1.2.1.2.2.1.6.$i).OIDValue
write-host "Interface $i MAC Address: " (get-hex $str)
}
By the way, the get-hex function in the above script was adapted from The Scripting Games' ABCs and 123s, which doesn't actually appear to work - but did teach me about the -f formatter.

Print | posted on Tuesday, August 21, 2007 9:52 AM

Feedback

# re: Retrieve Remote MAC Address in PowerShell

Left by Dan Mace at 12/15/2008 3:13 AM
Gravatar 2 errors in this script.
- There is no community
- you're putting the IP-address hard in $str.

# re: Retrieve Remote MAC Address in PowerShell

Left by Lance at 12/15/2008 10:07 AM
Gravatar The community is "public" by default. If you want to specify something else, just add the -community parameter.

# re: Retrieve Remote MAC Address in PowerShell

Left by Zax at 7/28/2009 8:48 AM
Gravatar Lance,

Ive been using this code, and I noticed it doesn't seem to convert my octet strings correctly in some cases. I am returning WWN's from storage devices via SNMP and after the conversion I compare it to the device's WWN and the two do not match. An example

My function based on your code:

function convert8str ($oid)
{
$len = $oid.length
$hex = @()
for($j=0;$j -lt $len;$j++)
{
$b = "{0:X}" -f ([int]$oid[$j])
$hex = $hex + $b
}
return $hex
}

Device WWN: 20:01:00:05:1e:80:d5:ef
Conversion: 20:1:0:5:1e:20AC:d5:ef

I would copy the octet string here, however the characters returned by the string are not supported.

Any thoughts on why this may be occurring?

# re: Retrieve Remote MAC Address in PowerShell

Left by zax at 7/29/2009 5:14 AM
Gravatar Nevermind my question. the /net cmdlets has a cmdlet called convert-data. the following function converts the octetstring correctly to a hex value.

function convert8str ($oid)
{
$hex = Convert-Data -Data $oid -To HEX
return $hex
}

Your comment:





 
 

Copyright © Lance Robinson

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski