Custom Foreach loop nslookup export to csv

7.8k views Asked by At

I'm new to PowerShell scripting. I am trying to make a script which resolves a list of DNS names to their IPs and outputs them as a CSV file. When a server is unresolvable it should be output to a separate file.

Here is my code:

$location
$location = Read-Host "CSV Path: "
$Names = Import-Csv -Path $location

foreach($n in $Names)
{
    try 
    {
        $output = $n.NAME
        $variable1 = [system.net.dns]::resolve($output) | Select 
        HostName,AddressList 
        $variable1
        $IP = $variable1.AddressList | Select-Object IPAddressToString
        $IPN = $IP.IPAddressToString
        $csv+=New-Object psobject -Property @{IPAddresse= $IPN;Name= 
        $output} | 
        Export-Csv \\filepath\Working.csv -NoTypeInformation
     }

    catch 
    {
        Write-host "$output is unreachable."
        Write-Output "$output" | Export-Csv \\Filepath\Unreachable.csv -
        Append -Encoding ASCII
    }

}

edit: The code was working quite well but now it says there is a delimiter mistake with the import but i dont know why this all of a sudden comes up as the code worked didnt got any edit and suddenly doesnt work anymore

1

There are 1 answers

0
Mark Wragg On BEST ANSWER

Here's a simplified/corrected version of your code:

$location = Read-Host "CSV Path: "
$Names = Import-Csv -Path $location

foreach($n in $Names)
{
    try {
        $Computer = [system.net.dns]::resolve($n.NAME) | Select HostName,AddressList 
        $IP = ($Computer.AddressList).IPAddressToString
        New-Object PSObject -Property @{IPAddress=$IP; Name=$Computer.HostName} | Export-Csv \\filepath\Working.csv -NoTypeInformation -Append
    } catch {
        Write-Host "$($n.NAME) is unreachable."
        Write-Output $n | Export-Csv \\Filepath\Unreachable.csv -Append -Encoding ASCII
    }
}