powershellforeach

while read in Powershell


File would look like this

Prename Lastname
Prename1 Lastname1
Prename2 Lastname2
...

In bash i would read that like this:

while read prename lastname do;
echo $prename
echo $lastname
done < text.txt

How could i do that in Powershell, i found that so far:

foreach($line in Get-Content .\text.txt) {
  write-host $line
}

But i need to store the line in multiple variables so i can work with them i dont need the line i need every word seperatet, can someone help me with this or display some documentation?

Greatfull for any help.


Solution

  • To read the file (assuming the first line contain the "column name") and store it in variable $fileContent you can do the following:

    $fileContent = Import-Csv -Path c:\path\to\text.txt -Delimiter ' '
    

    Iterate over the content and write out each column (assuming text.txt is separated by space):

    foreach($line in $fileContent) {
      Write-Host $line.Prename
      Write-Host $line.Lastname
    }
    

    Also note that if there is a line like:

    firstname secondname lastname
    

    $prename will be 'firstname' and $lastname will be 'secondname'