I have been having issues finding an answer to this question. SO I figured I would share what I have built with the masses. What I was trying to do was run the ARP -a command and capture the results to use in a TXT file for something else later. After much search, I was able to compile this.
I have included notes in the code to help those are less experienced to know what each section does.
But this code does these components
- Set your output path (if needed)
- Looks up current machines IP Address
- Breaks down the IP scheme to host only the first 3 octets. *There is a line of code in there that is # if you are using a machine with multiple NICs or IP Addresses to allow you to filter only the single one IF needed.
- Captures the ARP Table. *I have to 2 versions of the ARP capture. The first is IF you are going to filter by the devices IP scheme. This will help remove DNS and loop back entries. The second is if you want EVERYTHING.
- Outputs the results of IP Addresses to a txt file.
In my case, I am only using it to filter out the IP addresses. You may need it for other purposes. Good news is that it is easy to change the pieces to allow you to filter more towards your needs.
#Captures ARP Table then Displays ALL IPs that match the local computers IP Address
#Set the file you wish for the data to Output to
$OutputPath = "C:\Temp\Test.txt"
#Captures the devices IP Scheme and break it down, remove the Last Octet from the string
#This section is only used IF you are trying to filter the ARP by the local network the device is on.
[string[]]$ComputerName = $env:computername
$OrgSettings = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $ComputerName -EA Stop | ? { $_.IPEnabled }
$ip = $OrgSettings.IPAddress[0]
#IF (!($ip[1] -eq $null)) {$ip = $ip[0]}
$ip = (([ipaddress] $ip).GetAddressBytes()[0..2] -join ".") + "."
$ip = $ip.TrimEnd(".")
#Searches the ARP table for IPs that match the scheme and parses out the data into an Array (It removed the Devices IP from the list.)
Remove-Variable macarray
$macarray = @()
#(arp -a) -match $ip | Foreach{ #Use if needed for filtering results
(arp -a) | Foreach{ #Use this IF no filtering needed
$obj = New-Object PSObject -Property @{
IP = ($_ -split "\s+")[1]
MAC = ($_ -split "\s+")[2]
}
IF (!($obj.MAC -eq "---" -or $obj.MAC -eq "Address" -or $obj.MAC -eq $null -or $obj.MAC -eq "ff-ff-ff-ff-ff-ff")) {$macarray += $obj}
}
#Outputting the IP Addresses captured.
$macarray | Select -ExpandProperty "IP" | Out-file -FilePath $OutputPath -Force