Parsing Text file and placing contents into an Array Powershell

余生颓废 提交于 2021-01-28 14:11:24

问题


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?


回答1:


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
}



回答2:


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.



来源:https://stackoverflow.com/questions/24764622/parsing-text-file-and-placing-contents-into-an-array-powershell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!