Reading contents of line , comma delimited

  • Hello

    I am now into the world of Powershell. Get-Content gets the contents but how do i read the contents of a line (fixed number of colums in each line) ; I am been unsuccessfully trying to achieve the same. Is it possible to assign each line into a array and loop thru it? Does anyone have working code? Would appreciate if you can share it.

    TIA

  • Have a look at the command Import-CSV. It takes a comma delimited file as input and returns corresponding objects.

    The first line of the file needs to be a header containing column names for it to work.

    I've included both script and one-liner examples for you.

    First we need to create a test csv file

    "FirstName,Surname,Age`r`nBob,Smith,51`r`nPaul,Johnson,28`r`nNigel,Winterbottom,72`r`nBarbara,Andrews,36" > people.csv

    Script version

    # Import lines into object array

    $people = Import-Csv people.csv

    # Loop through and process each object

    foreach($person in $people)

    {

    $person.FirstName + " " + $person.Surname + " is " + $person.Age + " years old."

    }

    One liner version

    Import-Csv people.csv | ForEach-Object {$_.FirstName + " " + $_.Surname + " is " + $_.Age + " years old."}

    Hope this helps 🙂

    Paul.

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply