powershellimport-csvexport-csv

Import a CSV, run port connection, then export to new csv


I have a Sources.csv which has columns "Source," "Host" and "Port" (Source is just the name of the device I'm trying to connect to). My goal is to go line-by-line through this CSV, run a connection test to the IP and Port, then export to a new csv file to include these same columns as well as a new column "Reachable." This is what I have so far, but my csv file is filling up with all sorts of information that doesn't seem to make sense... So I'm curious if anyone can point me in the right direction:

$path = '.\Sources.csv'
$csv = Import-Csv -Path $path
Foreach($line in $csv){
    $TCPTest = Test-NetConnection $line.host -Port $line.port
    $Test = @{DataSource=$line.source; IP=$line.host; Port=$line.port; 
        Reachable=$TCPTest.TcpTestSucceeded}
    $Test | Export-Csv -Path .\SourceChecks.csv -append
    }

Solution

  • Santango's answer works all the way back to PowerShell version 1 (I think).

    If you can accept a dependency on PowerShell Version 3 (released in 2012), there is another option:

    $sourcesPath = '.\Sources.csv'
    
    $sources = Import-Csv $sourcesPath
    
    $sources | ForEach {
        $reachable = Test-NetConnection $_.host -Port $_.port -InformationLevel Quiet
    
        [PSCustomObject]@{
            Source = $_.Source
            Host = $_.Host
            Port = $_.Port
            Reachable = $reachable
        }
    } | 
    Export-Csv newpathtocsv.csv