Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
5.0k views
in Technique[技术] by (71.8m points)

powershell - 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.5k users

...