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

时间:2014-05-13 12:36:14

标签: object powershell text

我正在尝试找到一种将下面的数据转换为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
  做(
      $ 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
  }    直到($ count -eq $ text.count)
  $出

有简单的方法吗?

1 个答案:

答案 0 :(得分: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       

编辑:经过一番考虑,我认为我更喜欢这种模式:

$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]}
}