Powershell - 将文本字段转换为对象

Ser*_*gei 3 powershell text object

我试图找到一种优雅的方式将下面的数据转换为Powershell对象的集合,但不幸的是我无法找到一种简单的方法.有人能帮助我吗?

名称:ENC1
IPv4地址:172.16.2.101
链接设置:强制,100 Mbit,全双工
名称:ENC2
IPv4地址:172.16.2.103
链接设置:强制,100 Mbit,全双工
名称:ENC3
IPv4地址:172.16.2.103
链接设置:强制,100 Mbps,全双工
名称:ENC4
IPv4地址:172.16.2.104
链接设置:强制,100 Mbps,全双工

这就是我提出的.

$ out = @()
$ text = Get-Content input.txt
$ count = 0
do {
$ line =($ text | select -Skip $ count -first 3)
$ obj =""| 选择名称,IP,设置
$ obj.Name = $ line [0] .split(":")[1]
$ obj.IP = $ line [1] .split(":")[1]
$ obj.Settings = $ line [2] .split(":")[1]
$ out + = $ obj
$ count = $ count + 3
} until($ count -eq $ text.count)
$ out

这样做有简单的方法吗?

mjo*_*nor 7

使用开关:

$data = (@'
Name: ENC1
 IPv4 Address: 172.16.2.101
 Link Settings: Forced, 100 Mbit, Full Duplex
 Name: ENC2
 IPv4 Address: 172.16.2.103
 Link Settings: Forced, 100 Mbit, Full Duplex
 Name: ENC3
 IPv4 Address: 172.16.2.103
 Link Settings: Forced, 100 Mbps, Full Duplex
 Name: ENC4
 IPv4 Address: 172.16.2.104
 Link Settings: Forced, 100 Mbps, Full Duplex
'@).split("`n") |
foreach {$_.trim()}

Switch -Regex ($data) 
{
 '^Name: (.+)' {$obj = [PSCustomObject]@{Name=$Matches[1];IP=$null;Settings=$null}}
 '^IPv4 Address: (.+)' {$obj.IP = $matches[1]}
 '^Link Settings: (.+)' {$obj.Settings = $Matches[1];$obj}
}



Name                                 IP                                   Settings                            
----                                 --                                   --------                            
ENC1                                 172.16.2.101                         Forced, 100 Mbit, Full Duplex       
ENC2                                 172.16.2.103                         Forced, 100 Mbit, Full Duplex       
ENC3                                 172.16.2.103                         Forced, 100 Mbps, Full Duplex       
ENC4                                 172.16.2.104                         Forced, 100 Mbps, Full Duplex       
Run Code Online (Sandbox Code Playgroud)

编辑:经过一番考虑后,我觉得我更喜欢这种模式:

$DefValue = 'Parse error. Check input.'
Switch -Regex ($data) 
{
 '^Name: (.+)' {$obj;$obj = [PSCustomObject]@{Name=$Matches[1];IP=$DefValue;Settings=$DefValue}}
 '^IPv4 Address: (.+)' {$obj.IP = $matches[1]}
 '^Link Settings: (.+)' {$obj.Settings = $Matches[1]}
}
Run Code Online (Sandbox Code Playgroud)