2

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?

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

3 Comments

Edit: I missed the important -Delimiter bit that makes it work with the pipe character! Updated.
Quick question, is there a way to anonymously get the strings from item object? I have tried $item[n] and $item.fieldn, while the latter didnt' through me an exception It still didn't work. I am assuming if I add headers to the import command, that is what it is expecting?
@DmainEvent I do not know of a way, and cannot find one with quick looking. I recommend you post a new question and other people can see it too. (But as a side comment, you must have headers as the first line in the file, or using Import-CSV -Header ..., otherwise it will take the first line of the file as header names and you will miss that row of data).
1

If your data is flat or unstructured, but has a pattern such as delimited by a space or comma and no carriage returns or line feeds, you can use the Split() method.

PS>$data = "prodServ1a prodServ1b prodServ1c"

PS>$data
prodServ1a prodServ1b prodServ1c

PS>$data.Split(" ")
prodServ1a
prodServ1b
prodServ1c

Works particularly well with someone sending you a list of IP addresses separated by a comma.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.