For*_*ica 2 powershell parsing
我正在解析来自磁盘阵列的文本输出,该磁盘阵列以可预测的格式列出有关 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
Run Code Online (Sandbox Code Playgroud)
这在整个文件中重复,每组之间有一个换行符。我想确定一个组,解析四行中的每一行,创建一个新的 PSObject,将每行的值添加为新的 NoteProperty,然后将新对象添加到集合中。
我能想到的是,一旦我确定了四行块中的第一行,那么如何处理第二行、第三行和第四行中的文本。我遍历每一行,找到一个块的开始,然后处理它。到目前为止,这是我所拥有的,并附有魔法所在的评论:
$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
}
}
Run Code Online (Sandbox Code Playgroud)
我搜索了 Google 和 StackOverflow,试图弄清楚如何引用我正在迭代的对象的行号,但我无法弄清楚。我可能过于依赖 foreach 循环,所以这影响了我的思考,我不知道。
至于你说的,我想你想太多的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
}
}
Run Code Online (Sandbox Code Playgroud)
while 循环可能更干净,因为这样当您遇到这种情况时,您可以将 $i 增加 4 而不是 1,但是由于其他 3 行不会触发“if”语句……没有危险,只有几行浪费的周期。
| 归档时间: |
|
| 查看次数: |
16131 次 |
| 最近记录: |