Tech Blog‎ > ‎

PowerShell - Get MAC Address Of Any Remote IP

posted Feb 9, 2010, 9:27 AM by Victor Zakharov
Here is a PowerShell one-liner:

#change/assign $hostIp to a valid IP address
(gwmi -Class Win32_NetworkAdapterConfiguration | where { $_.IpAddress -eq $hostIp }).MACAddress

If you need to dynamically resolve a host IP from its name:

#change/assign $Computer to a valid host identifier
$hostIp = [System.Net.Dns]::GetHostByName($Computer).AddressList[0].IpAddressToString

The whole script may look like the following:

param ( $Computer , $Credential )
#to make it work without parameters
if($Computer -eq $null) { $Computer = $env:COMPUTERNAME }
#program logic
$hostIp = [System.Net.Dns]::GetHostByName($Computer).AddressList[0].IpAddressToString
if($Credential) {
    $Credential = Get-Credential $Credential
    $wmi = gwmi -Class Win32_NetworkAdapterConfiguration -Credential $Credential -ComputerName $Computer
} else {
    $wmi = gwmi -Class Win32_NetworkAdapterConfiguration -ComputerName $Computer
}
return ($wmi | where { $_.IpAddress -eq $hostIp }).MACAddress

Input parameters

$Computer, one of the following:
1 - null value (script will work locally)
2 - computer name, FQDN or IP address (will be resolved to IP, if needed).

$Credentials, one of the following:
1 - null value (will assume local user account)
2 - user name with or without domain specified (will prompt for password)
3 - variable with saved credentials (i.e. $Credential = Get-Credential), for silent access

Because it's WMI based, $Computer can be from any network. But you must have necessary account permissions and firewall rules. For cross-domain operation, make sure you either specify full credentials with domain qualifier or have a local account with the same name and password on remote machine.
Comments