Question

I am trying to find an elegant way of transforming data below into collection of Powershell objects but unfortunately I am unable to find a simple way of doing it. Would someone be able to help me here?

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

This is what I came up with.

$out = @()
$text = Get-Content input.txt
$count = 0
do {
$line = ($text | select -Skip $count -first 3)
$obj = "" | Select Name,IP,Settings
$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

Is there simplier way of doing it?

Was it helpful?

Solution

Using a Switch:

$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       

Edit: after some consideration, I think I like this pattern better:

$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]}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top