Search code examples
powershellloopscsvforeachread-eval-print-loop

how to iterate each row of CSV data using ForEach?


Looking to use ForEach here specifically.


reading in and loading a csv file for sample data:

PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $a = Import-Csv  -Path ./alphabet.csv
PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $a[7].psobject.Properties.name
symbol
code word
morse code
phonetic
PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $a[7].'code word'             
Hotel
PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $a.'code word'   
Alfa/Alpha
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliett
Kilo
..
Yankee
Zulu
PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> $numbers=(1,2,3,4,5)
PS /home/nicholas/powershell/regex> 
PS /home/nicholas/powershell/regex> foreach ($number in $numbers){ echo $number}
1
2
3
4
5
PS /home/nicholas/powershell/regex> 

but how would foreach be used to iterate through each row? Something like:

$a.forEach($code_word in $a.'code word'){echo $code_word}

looking to use ForEach here specifically, preferably in one-line which can be used in the REPL console.


Solution

  • There are two instances of Foreach in Powershell. One is a keyword, and the other is an alias for Foreach-object. The easiest way to loop through a csv file is to import-csv, send the result through the pipeline, and use Foreach-Object to introduce the loop. The special symbol "%" is also shorthand for Foreach-Object.

    Try this:

    Import-csv -path myfile.csv |
        Foreach-object {
          $sym = $_.symbol
          $code = $_.'code word'
          "The code word for $sym is $code"
        }
    

    On this csv file.

    symbol,code word,morse code,phonetic
    A,Alfa/Alpha,"● ▬",AL FAH
    B,Bravo,"▬ ● ● ●",BRAH VOH
    C,Charlie,"▬ ● ▬ ●",CHAR LEE
    D,Delta,"▬ ● ●",DELL TAH
    E,Echo,"●",ECK OH
    F,Foxtrot,"● ● ▬ ●",FOKS TROT
    G,Golf,"▬ ▬ ●",GOLF
    Z,Zulu,"▬ ▬ ▬ ▬ ▬",ZOO LOO
    H,Hotel,"● ● ● ●",HOH TELL