I have the following PowerShell script output :
{
"parameter": "p1",
"device": "d1",
"assignee": "me"
}
{
"Name": "N",
"device": "d4"
}
{
"alart": "C1"
}
I want to get the first set only :
{
"parameter": "p1",
"device": "d1",
"assignee": "me"
}
I tried ConvertTo-Json but it doesn't work as I expected.
note: the length of each set can be different each time so I cant hard code the number of selected lines.
$output[0..3]
the above code will not work in my case
CodePudding user response:
A simple approach would be to collect the script's output lines (you state that the script emits its output line by line) only up until the first empty line is encountered, using a switch
statement.
$firstParagraph =
switch (.\yourScript.ps1) {
'' { break } # first empty line found; stop processing
default { $_ } # non-empty line: pass it through.
}
If you also need to detect blank, i.e. all-whitespace lines:
$firstParagraph =
switch -Regex (.\yourScript.ps1) {
'\S' { $_ } # non-blank line: pass it through
default { break } # first blank line: stop processing
}
If there may be no empty or blank lines between the JSON objects and you can rely on }
on its own line closing the first object:
$firstParagraph =
switch -Regex (.\yourScript.ps1) {
'^\s*}\s*$' { $_; break } # closing line of the first object: emit and stop processing
'\S' { $_ } # other non-blank line: pass it through
default { break } # first blank line: stop processing
}
Finally, you can repeatedly try to parse the lines collected so far as JSON, and stop processing once parsing succeeds; note that this solution returns an object representing the first JSON object, as returned by ConvertFrom-Json
:
$linesSoFar = ''
$firstObject =
switch -Regex (.\yourScript.ps1) {
'}' { # potentially the end of a complete JSON object
$linesSoFar = "`n" $_
# Try to convert from JSON and output the resulting object,
# if successful.
ConvertFrom-Json -ErrorAction Ignore $linesSoFar
if ($?) { break } # Conversion succeeded, stop processing.
}
default { $linesSoFar = "`n" $_ } # first blank line: stop processing
}