I am making a Powershell CmdLet, and one function is getting info from network devices
I just want it to output the device hostname, and weather or not the device has connectivity.
Here's my current code:
$devlist = arp -a
$devlength = $devlist.Length - 1
foreach($i in 3..$devlength){
$devlist[$i] = $devlist[$i].Substring(0,24) | ForEach-Object { $_ -replace ' ','' }
ping -n 1 -a $devlist[$i]
}
I want the output format to be something like this:
Device host name (if received) | Device IP address | Has connectivity (yes/no)
You can try something a long the lines of:
(arp -a | Select-Object -skip 10).Trim() -replace "(\s+){3}","," |
ConvertFrom-Csv |
ForEach-Object -Process `
{
[PSCustomObject]@{
IPAddress = $_.{Internet Address}
HostName = (Resolve-DnsName $_.{Internet Address} -ErrorAction SilentlyContinue).NameHost
Status = if(Test-Connection -ComputerName $_.{Internet Address} -Count 1 -Quiet) {'Online'} else {'Offline'}
}
}
I took the approach as converting the entirety of the returned values, as an object to make it easier to work with.
EDIT: If you're looking to make this accessible to other users, you have to account on how their Arp Table is set, and how many interfaces there are. So attempting to guess where the column headers start, is not the best solution. So here's what you can do to get around that:
((arp -a).Trim().Where{$_ -match "^\d+"}) -replace "\s+","," |
ConvertFrom-Csv -Header "IPAddress","MACAddress","Type" |
ForEach-Object -Process `
{
[PSCustomObject]@{
IPAddress = $_.IPAddress
HostName = (Resolve-DnsName $_.IPAddress -ErrorAction SilentlyContinue).NameHost
Status = if (Test-Connection -ComputerName $_.IPAddress -Count 1 -Quiet) {'Online'} else {'Offline'}
}
}