text-files - 解析文本文件并将内容放入数组 Powershell

标签 text-files powershell-2.0

我正在寻找一种方法来解析文本文件并将结果放入 powershell 中的数组中。

我知道 select-string -path -pattern 会得到所有匹配模式的字符串。但是如果我已经有一个结构化的文本文件,可能是管道删除的,每行都有新条目怎么办。像这样:

产品服务1a 产品服务1b 产品服务1c

C:\dir\serverFile.txt

我如何将这些服务器中的每一个放入我可以循环访问的 powershell 数组中?

最佳答案

你说“竖线分隔,就像这样”,但你的例子不是竖线分隔的。我想是的,那么您需要使用 Import-CSV commandlet。例如如果数据文件包含这个:

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

然后这段代码:

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

将导入并拆分它,并添加标题:

$data

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

然后就可以使用了

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

关于text-files - 解析文本文件并将内容放入数组 Powershell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24764622/

相关文章:

java - 谁能帮我使用 StartingClass 中的 loadMap() 方法加载 map (文本文件)?

powershell - 在 Powershell 中,按记录类型拆分大型文本文件的最有效方法是什么?

excel - 如何通过 VBA 识别 UNIX 文本文件中的隐藏回车符?

powershell - 使用Get-childitem获取最近3天内修改的文件列表

powershell - 以多个用户身份运行Powershell脚本

powershell - 使用Powershell脚本获取字符串中具有特定日期的文件

loops - 如何使用从文本文件接受参数的循环创建批处理文件?

java - 当我尝试使用 BufferedReader 跳过多行时,为什么会出现 StringIndexOutOfBoundsException?

powershell - PowerShell 中的一元 "Not"或位翻转运算符?

powershell - 为什么 get-process -computername 会返回无法连接到远程计算机错误?