将文本文件中的每个项目放入数组中,但检测标题/标题

问题描述 投票:0回答:1

我有包含

的文本文件

名字:xxx 姓氏: yyy 登录:abcd

它还有许多其他定义的条目,但都具有相同的格式标题:数据

我想在 PowerShell 中使用数组来读取这些内容并且愿意这样做

$array.名字 $array.Login

让我获取数据。

这可以做到吗?

我们目前使用很长的正则表达式来吐出数据,但这变得很笨拙,希望简化它。

powershell
1个回答
0
投票

我想在 PowerShell 中使用数组来读取这些内容并且愿意这样做

数组只是多个某物的固定大小的容器,它们本身并没有真正做任何事情。

如果您想要一个具有任意命名属性(如

firstname
login
)的事物,那么您需要一个自定义 对象

您可以使用

-match
正则表达式运算符来识别和提取每行中的标签和值,如下所示:

$filePath = 'C:\path\to\file.txt'

# create an ordered dictionary to temporarily hold the label-value pairs
$properties = [ordered]@{}

# read the file into memory line-by-line
Get-Content $filePath |ForEach-Object {
  # test whether the line matches the `label: value` format
  if ($_ -match '^([^:]+):\s*(.*)$') {
    # ... and if so, extract the values matched by the capture groups
    $properties[$Matches[1]] = $Matches[2]
  }
}

# finally convert the ordered dictionary to an object
$myObject = [pscustomobject]$properties

$myObject
现在包含一个对象,其属性以文件中找到的标题标签命名,因此您现在可以引用
$myObject.Login
等。

© www.soinside.com 2019 - 2024. All rights reserved.