As @alroc notes in the commentary on the question, it is possible that the objects are accessible by the OP, given that they claim that the output is βfrom the Powershell requestβ - if so, simply reformatting the array of objects using regular cmdlets is an option.
On the contrary, this answer assumes that only the textual representation printed in the question is available.
Dave Sexton's answer is a simpler and more elegant choice if:
- input has no empty values ββ(sample input OP is used).
- the input file is small enough to be read into memory as a whole.
Consider the approach below to avoid the problems above and / or if you want more control over how input is converted to user objects , especially with respect to creating properties with types other than [string] : extend the toObj() function below (as written, that's it properties are also just strings).
Get-Content File | % ` -begin { function toObj([string[]] $lines) { $keysAndValues = $lines -split '(?<=^[^ :]+)\s*: ' $htProps = @{} for ($i = 0; $i -lt $keysAndValues.Count; $i += 2) { $htProps.($keysAndValues[$i]) = $keysAndValues[$i+1] } return [PSCustomObject] $htProps } $lines = @() } ` -process { if ($_.trim() -ne '') { $lines += $_ } else { if ($lines) { toObj $lines } $lines = @() } } ` -end { if ($lines) { toObj $lines } } | Format-Table
Explanation:
Uses ForEach-Object ( % ) with separate begin , process and end blocks.
-begin executed once at the beginning:
Defines a helper function toObj() that converts a block of adjacent non-empty input strings into a single user object.
toObj() splits the array of strings into an array of adjacent key values, converts this array into a hash table, which is then converted to a user object.
Initializes an array of $lines , which will store the lines of one block of adjacent non-empty input lines
The -process block executed for each line of input:
If the input line is not empty: adds it to the current block of adjacent non-empty input lines stored in the $lines array.
Otherwise: sends the current block to toObj() to convert to a custom object, and then flushes the $lines array to start the next block. Essentially, toObj() (starting non-empty lines) is called for each paragraph.
The -end block executed once at the end:
- Sends the last paragraph to
toObj() for conversion to a custom object.
Finally, the resulting array of user objects is passed to the Format-Table .
source share