解析文本文件并将内容放入数组 Powershell [英] Parsing Text file and placing contents into an Array Powershell
问题描述
我正在寻找一种方法来解析文本文件并将结果放入 powershell 中的数组中.
I am looking for a way to parse a text file and place the results into an array in powershell.
我知道 select-string -path -pattern 会得到所有匹配某个模式的字符串.但是如果我已经有一个结构化的文本文件,也许是管道分隔的,每行都有新的条目.像这样:
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:
prodServ1aprodServ1bprodServ1c
prodServ1a prodServ1b prodServ1c
C:\dir\serverFile.txt
C:\dir\serverFile.txt
如何将这些服务器中的每一个放入我可以循环访问的 powershell 数组中?
How can I place each of those servers into an array in powershell that I can loop through?
推荐答案
您说管道分隔,像这样",但您的示例不是管道分隔的.我想是这样,那么您需要使用 Import-CSV
命令行开关.例如如果数据文件包含这个:
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
然后这段代码:
$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
然后你就可以使用
foreach ($item in $data) {
$item.SerialNo
}
这篇关于解析文本文件并将内容放入数组 Powershell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!