我在日志文件中有一个NetApp日志输出,格式如下。
DeviceDetails.log文件内容
/vol/DBCXARCHIVE002_E_Q22014_journal/DBCXARCHIVE002_E_Q22014_journal 1.0t (1149038714880) (r/w, online, mapped)
Comment: " "
Serial#: e3eOF4y4SRrc
Share: none
Space Reservation: enabled (not honored by containing Aggregate)
Multiprotocol Type: windows_2008
Maps: DBCXARCHIVE003=33
Occupied Size: 1004.0g (1077986099200)
Creation Time: Wed Apr 30 20:14:51 IST 2014
Cluster Shared Volume Information: 0x0
Read-Only: disabled
/vol/DBCXARCHIVE002_E_Q32014_journal/DBCXARCHIVE002_E_Q32014_journal 900.1g (966429273600) (r/w, online, mapped)
Comment: " "
Serial#: e3eOF507DSuU
Share: none
Space Reservation: enabled (not honored by containing Aggregate)
Multiprotocol Type: windows_2008
Maps: DBCXARCHIVE003=34
Occupied Size: 716.7g (769556951040)
Creation Time: Tue Aug 12 20:24:14 IST 2014
Cluster Shared Volume Information: 0x0
Read-Only: disabled
其中输出只有2个设备,它在日志文件中附加了多于x个设备。
我只需要每个模块的4个细节, 第一行包含3个所需的详细信息
设备名称: / vol / DBCXARCHIVE002_E_Q22014_journal / DBCXARCHIVE002_E_Q22014_journal
总容量: 1.0t(1149038714880)
状态:(黑白,在线,已映射)
我需要的第4个细节是占用尺寸:1004.0g(1077986099200)
我不仅仅是编码的初学者,并尝试使用以下代码实现这一点,但它没有多大帮助:/
$logfile = Get-Content .\DeviceDetails.log
$l1 = $logfile | select-string "/vol"
$l2 = $logfile | select-string "Occupied Size: "
$objs =@()
$l1 | ForEach {
$o = $_
$l2 | ForEach {
$o1 = $_
$Object22 = New-Object PSObject -Property @{
'LUN Name , Total Space, Status, Occupied Size' = "$o"
'Occupied Size' = "$o1"
}
}
$objs += $Object22
}
$objs
答案 0 :(得分:0)
$obj = $null # variable to store each output object temporarily
Get-Content .\t.txt | ForEach-Object { # loop over input lines
if ($_ -match '^\s*(/vol.+?)\s+(.+? \(.+?\))\s+(\(.+?\))') {
# Create a custom object with all properties of interest,
# and store it in the $obj variable created above.
# What the regex's capture groups - (...) - captured is available in the
# the automatic $Matches variable via indices starting at 1.
$obj = [pscustomobject] @{
'Device Name' = $Matches[1]
'Total Space' = $Matches[2]
'Status' = $Matches[3]
'Occupied Size' = $null # filled below
}
} elseif ($_ -match '\bOccupied Size: (.*)') {
# Set the 'Occupied Size' property value...
$obj.'Occupied Size' = $Matches[1]
# ... and output the complete object.
$obj
}
} | Export-Csv -NoTypeInformation out.csv
- 请注意Export-Csv
默认为ASCII输出编码;使用-Encoding
参数更改它
- 要仅提取(...)
和Total Space
列的Occupied Size
内的数字,请使用
$_ -match '^\s*(/vol.+?)\s+.+?\s+\((.+?)\)\s+(\(.+?\))'
和
而是$_ -match '\bOccupied Size: .+? \((.*)\)'
。
功能
请注意此解决方案如何逐行处理输入文件,这会使内存耗尽,但通常会牺牲性能。
至于您尝试的内容:
您将整个输入文件收集为内存中的数组($logfile = Get-Content .\DeviceDetails.log
)
然后将此数组过滤两次到并行数组中,其中包含相应的感兴趣行。
当您尝试嵌套处理这两个数组时出现问题。您必须枚举并行,而不是嵌套,因为它们的相应索引包含匹配的条目。
此外:
'LUN Name , Total Space, Status, Occupied Size' = "$o"
之类的行会创建一个名为LUN Name , Total Space, Status, Occupied Size
的单属性,这不是意图。