This original question was not about powershell. I am assuming these base premises:
- We are running Windows 7
- We want to parse the result of systeminfo utility that comes with Windows 7
- We want to extract information about network adapters from the output and put it into some data structure for further processing.
Now, I know that there are better ways of getting Network card information than running systeminfo and parsing the output. My interest is not in this particular utility. I'm considering a generic task of parsing / format some text in powershell. I feel that powershell is well suited for this kind of tasks, maybe better than C# (depending on particular requirements). This is why I offer my answer in powershell to the original question.
My question, though is this. I always feel that some of powershell syntax is a bit cumbersome. How would you improve my code? Note that the code does not have to return exactly the same results in exactly the same structure. I'm looking for tricks that can help with text parsing / processing. I've seen once and again community's ingenuity in approaching a lot of task. I've seen simple solutions to complex problems that are not at all obvious until someone shows you how. This is why I'm asking.
Here is the code:
$networkCards = systeminfo | ForEach-Object {$a=0} {
if ($_.startswith("Network Card(s)")) {$a=1} else {if ($a) {$_}}
}
$networkCards | ForEach-Object {$data=@{}} {
if ($_.trim().startswith("[")) {
$c = $_.trim(); $data[$c] = @()} else {$data[$c] += $_.trim()
}
}
#Now we have a hash table with the keys as requested in the question
#and the values are lists of separate strings, but those can be easily
#concatenated if needed. Let's display it:
$data