powershellcsvforeach

Need to create a foreach loop for a CSV file, using 2 variables, in Powershell


I am new to coding and most of my experience is with Python. I am working on a simple powershell script that runs a Test-NetConnection on IP address and ports in a CSV file.

IP Port
1.1.1.1 22
1.1.1.2 25
1.1.1.3 80
1.1.1.4

Each IP needs to be tested with each Port

What I have so far is this, not sure if I need to create a new list with each IP/Port combination, and then run a foreach on them:

$csv_path = Read-Host -Prompt "Enter file path"

$csv = Import-Csv -Path "$csv_path"

foreach($item in $csv){
    "{0} = {1}" -f $item.IP,$item.Port
    Test-NetConnection -ComputerName "$item.IP" -Port "$item.Port" -InformationLevel Detailed
}

Solution

  • PowerShell has a handy feature called Member-Access Enumeration that you can use here.

    In short, if you access a property or method on an array object (for example your $csv variable) it will invoke that property or method on all items in the array and return a new array with the all results in it.

    For example with this test data:

    PS> $csv = @"
    IP,      Port
    1.1.1.1, 22
    1.1.1.2, 25
    1.1.1.3, 80
    1.1.1.4,
    "@ | ConvertFrom-Csv
    

    if you invoke $csv.IP you get an array of all the IP properties:

    PS> $csv.IP
    1.1.1.1
    1.1.1.2
    1.1.1.3
    1.1.1.4
    

    and the same for $csv.Port:

    PS> $csv.Port
    22
    25
    80
    

    (note that the "Port" output has 4 items in it - there's a non-printing $null in the fourth index)

    We can use this to do a nested loop over all the combinations of IP and Port like this:

    # use member-access enumeration to get ip and port arrays,
    # and filter out $null or empty string values
    $ips   = $csv.IP | where-object { $_ }
    $ports = $csv.Port | where-object { $_ }
    
    foreach( $ip in $ips )
    {
        foreach( $port in $ports )
        {
    
            "{0} = {1}" -f $ip, $port
            Test-NetConnection -ComputerName $ip -Port $port -InformationLevel Detailed
    
        }
    }