Friday, 7 July 2017

PowerShell: Get Hostname Following Successful Ping

The script below will attempt to ping a range of IP addresses and if successful, will return their hostnames;
1..10 | % {Test-NetConnection -ComputerName x.x.x.$_ -ErrorAction SilentlyContinue -WarningAction SilentlyContinue } | Select ComputerName,RemoteAddress,PingSucceeded, `@{ Name = 'HostName'; Expression = { If ($_.PingSucceeded){([System.Net.Dns]::gethostentry($_.computername)).HostName}Else{$null} } } | FT -AutoSize
Replace the "1..10" at the start of the command with the range of IP addresses you wish to scan and update the -ComputerName parameter with the IP you wish to scan (e.g. 10.100.1.$_)

No comments:

Post a Comment