Parsing Text file and placing contents into an Array Powershell

powershell-2.0, text-files

Solution

You say 'pipe delimited, like so' but your example isn't pipe delimited. I'll imagine it is, then you need to use the `Import-CSV` commandlet. e.g. if the data file contains this:

prodServ1a|4|abc
prodServ1b|5|def
prodServ1c|6|ghi

then this code:

$data = Import-Csv -Path test.dat -Header "Product","Cost","SerialNo" -Delimiter "|"

will import and split it, and add headers:

$data

Product                    Cost                       SerialNo
-------                    ----                       --------
prodServ1a                 4                          abc
prodServ1b                 5                          def
prodServ1c                 6                          ghi

Then you can use

foreach ($item in $data) {
    $item.SerialNo
}

Problem

I am looking for a way to parse a text file and place the results into an array in powershell. I know select-string -path -pattern will get all strings that match a pattern. But what if I already have a structured textfile, perhaps pipe delimminated, with new entries on each line. Like so: prodServ1a prodServ1b prodServ1c C:\dir\serverFile.txt How can I place each of those servers into an array in powershell that I can loop through?

Original source