我正在解析磁盘阵列的文本输出,该阵列以可预测的格式列出有关 LUN 快照的信息。在尝试了所有其他方法以可用的方式从数组中获取这些数据之后,我唯一能做的就是生成这个文本文件并解析它。输出如下所示:
SnapView logical unit name: deleted_for_security_reasons
SnapView logical unit ID: 60:06:01:60:52:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX:XX
Target Logical Unit: 291
State: Inactive
这会在整个文件中重复,每组之间有一个换行符。我想识别一个组,解析四行中的每一行,创建一个新的 PSObject,将每行的值添加为新的 NoteProperty,然后将新对象添加到集合中。
我能弄清楚的是,一旦我确定了四行 block 中的第一行,如何处理第二行、第三行和第四行中的文本。我循环遍历每一行,找到 block 的开头,然后对其进行处理。这是我到目前为止所得到的,以及神奇之处的评论:
$snaps = get-content C:\powershell\snaplist.txt
$snapObjects = @()
foreach ($line in $snaps)
{
if ([regex]::ismatch($line,"SnapView logical unit name"))
{
$snapObject = new-object system.Management.Automation.PSObject
$snapObject | add-member -membertype noteproperty -name "SnapName" -value $line.replace("SnapView logical unit name: ","")
#Go to the next line and add the UID
#Go to the next line and add the TLU
#Go to the next line and add the State
$snapObjects += $snapObject
}
}
我搜索了 Google 和 StackOverflow,试图找出如何引用正在迭代的对象的行号,但我无法弄清楚。我可能过于依赖 foreach 循环,所以这影响了我的思维,我不知道。
最佳答案
正如你所说,我认为当你应该考虑for时,你却想得太多foreach。以下修改应该更符合您正在寻找的内容:
$snaps = get-content C:\powershell\snaplist.txt
$snapObjects = @()
for ($i = 0; $i -lt $snaps.length; $i++)
{
if ([regex]::ismatch($snaps[$i],"SnapView logical unit name"))
{
$snapObject = new-object system.Management.Automation.PSObject
$snapObject | add-member -membertype noteproperty -name "SnapName" -value ($snaps[$i]).replace("SnapView logical unit name: ","")
# $snaps[$i+1] Go to the next line and add the UID
# $snaps[$i+2] Go to the next line and add the TLU
# $snaps[$i+3] Go to the next line and add the State
$snapObjects += $snapObject
}
}
while 循环可能更干净,因为当遇到这种情况时,您可以将 $i 加 4 而不是 1,但由于其他 3 行不会触发“if”语句...因此没有危险,只是浪费了几个周期。
关于parsing - Powershell中的文本解析: Identify a target line and parse the next X lines to create objects,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9136967/