Get-HostfromIP

Home   »   Get-HostfromIP

function Get-HostfromIP
{
    Param
    (
         [Parameter(Mandatory=$true, Position=0)]
         [string] $importpath,
         
         [Parameter(Mandatory=$true, Position=1)]
         [string] $exportpath
         
    )

    <#
        .SYNOPSIS
        Resolves host names for IP addresses.

        .DESCRIPTION
        Adds a csv and loops through the list to gather the host-name for an IP address in the list.
        IP address is pinged for online/offline status 
        Data is collected, printed on the screen and exported to a new CSV.

        .PARAMETER importpath
        Specifies the path where the initial CSV can be imported from.

        .PARAMETER exportpath
        Specifies the path where the result is exported to a CSV.

        .INPUTS
        None. 

        .OUTPUTS
        CSV files with status of IP addresses and resolved host name

        .EXAMPLE
        PS> Get-HostfromIP -importpath  "C:\Temp\nslookup.csv" -exportpath c:\temp\dns_resolved.csv
        8.8.8.8 ..... checking
        8.8.2.2 ..... checking

        IP      Host-Name    Status 
        --      ---------    ------ 
        8.8.8.8 dns.google   online 
        8.8.2.2 no dns found offline

        .LINK
        N/A

    #>


$IPList = Import-Csv -Path $importpath

$ResolvList = @()

foreach ($ip in $IPList)
    {
    $ResolvItem = New-Object -TypeName PSObject
    $ResolvItem | add-member -Name 'IP' -MemberType NoteProperty -Value $ip.IP
    write-host $ip.IP  "..... checking"
    try 
        {
        $ResolvItem | Add-Member -Name 'Host-Name' -MemberType NoteProperty -value (Resolve-DnsName -Name $ip.IP -ErrorAction Stop).NameHost
        }
    catch
        {
        $ResolvItem | Add-Member -Name 'Host-Name' -MemberType NoteProperty -value "no dns found"
        }

    try
        {
        if (Test-Connection -ComputerName $ip.IP -Count 1 -ErrorAction Stop)
            {        
            $ResolvItem | Add-Member -Name 'Status' -MemberType NoteProperty -value 'online'
            }
        }
    catch
        {
        $ResolvItem | Add-Member -Name 'Status' -MemberType NoteProperty -value 'offline'
        }
    
    $ResolvList += $ResolvItem

    }
    $ResolvList | Format-Table
    $ResolvList | Export-csv -Path $exportpath  -NoTypeInformation -Force
}

Get-HostfromIP -importpath  "C:\Temp\nslookup.csv" -exportpath c:\temp\dns_resolved.csv

Leave a Reply

Your email address will not be published. Required fields are marked *