如何使用split和substring
和foreach
处理数组以输出以下信息。
我尝试使用split和substring
。但仍然无法正常工作。谢谢。
$item=$item.ToString()
$driveID=$item.Substring(0,26)
$ID=($driveID.Split(":")[-1]).trim()
$status=$item.Substring(27,$item.Length-1-27)
$stauts1=($status.split(",")[-1]).trim()
输入【数组】:
physicaldrive 1I:1:9 (port 1I:box 1:bay 9, SAS HDD, 900 GB, OK)
physicaldrive 1I:1:10 (port 1I:box 1:bay 10, SAS HDD, 900 GB, OK)
physicaldrive 1I:1:11 (port 1I:box 1:bay 11, SAS HDD, 2.4 TB, OK, spare)
physicaldrive 1I:1:12 (port 1I:box 1:bay 12, SAS HDD, 900 GB, OK, shared spare)
预期输出:
DriveID DriveStatus
9 OK
10 OK
11 OK
12 OK
答案 0 :(得分:1)
以下假设DriveID
是单词bay
之后的数字。该代码将捕获命名的捕获组,并使用它们来创建PSCustomObject。然后将其发送到$DriveInfo
集合,并最终显示在屏幕上。此时,您可以轻松导出它。 [咧嘴]
#region >>> fake reading in a text file
# in real life, use Get-Content
$InStuff = @'
physicaldrive 1I:1:9 (port 1I:box 1:bay 9, SAS HDD, 900 GB, OK)
physicaldrive 1I:1:10 (port 1I:box 1:bay 10, SAS HDD, 900 GB, OK)
physicaldrive 1I:1:11 (port 1I:box 1:bay 11, SAS HDD, 2.4 TB, OK, spare)
physicaldrive 1I:1:12 (port 1I:box 1:bay 12, SAS HDD, 900 GB, OK, shared spare)
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a text file
$DriveInfo = $InStuff.ForEach({
$Null = $_ -match '^.+:bay (?<DriveID>\d+), .+b, (?<Status>.+).+$'
[PSCustomObject]@{
DriveID = $Matches.DriveID
Status = $Matches.Status.Split(',')[0]
}
})
$DriveInfo
输出...
DriveID Status
------- ------
9 OK
10 OK
11 OK
12 OK