Bulk nslookup script

USAGE:

.\Resolve-IPs.ps1 -InputPath .\ips.txt -OutputPath .\resolved.csv


SCRIPT - 

param(
    [Parameter(Mandatory=$true)]
    [string]$InputPath,
    [Parameter(Mandatory=$true)]
    [string]$OutputPath
)

# Ensure input exists
if (-not (Test-Path -Path $InputPath)) {
    Write-Error "Input file not found: $InputPath"
    exit 1
}

# Create output directory if needed
$dir = Split-Path -Path $OutputPath -Parent
if ($dir -and -not (Test-Path $dir)) {
    New-Item -ItemType Directory -Path $dir | Out-Null
}

# Read IPs (ignore empty lines and lines starting with #)
$ips = Get-Content -Path $InputPath | ForEach-Object { $_.Trim() } | Where-Object { $_ -and ($_ -notmatch '^\s*#') }

# Prepare results
$results = @()

foreach ($ip in $ips) {
    $hostname = $null
    $status = "OK"

    try {
        # Reverse lookup
        $entry = [System.Net.Dns]::GetHostEntry($ip)
        $hostname = $entry.HostName
    }
    catch {
        $hostname = ""
        $status = "NXDOMAIN/No PTR or lookup failed"
    }

    $results += [PSCustomObject]@{
        IP       = $ip
        Hostname = $hostname
        Status   = $status
    }
}

# Export CSV
$results | Export-Csv -NoTypeInformation -Path $OutputPath -Encoding UTF8

Write-Host "Done. Results written to $OutputPath"

No comments: