我有以下 PowerShell 腳本輸出:
{
"parameter": "p1",
"device": "d1",
"assignee": "me"
}
{
"Name": "N",
"device": "d4"
}
{
"alart": "C1"
}
我只想得到第一套:
{
"parameter": "p1",
"device": "d1",
"assignee": "me"
}
我嘗試 了ConvertTo-Json,但它沒有像我預期的那樣作業。
注意:每組的長度每次都可能不同,所以我不能硬編碼所選行的數量。
$output[0..3]
上面的代碼在我的情況下不起作用
uj5u.com熱心網友回復:
一種簡單的方法是使用陳述句收集腳本的輸出行(您宣告腳本逐行發出其輸出)直到遇到第一個空行switch。
$firstParagraph =
switch (.\yourScript.ps1) {
'' { break } # first empty line found; stop processing
default { $_ } # non-empty line: pass it through.
}
如果您還需要檢測blank,即所有空白行:
$firstParagraph =
switch -Regex (.\yourScript.ps1) {
'\S' { $_ } # non-blank line: pass it through
default { break } # first blank line: stop processing
}
如果 JSON 物件之間可能沒有空行或空行,您可以依靠} 它自己的行來關閉第一個物件:
$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
}
最后,可以反復嘗試決議目前收集到的行為JSON,決議成功后停止處理;請注意,此解決方案回傳一個表示第一個 JSON 物件的物件,由以下方式回傳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
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/534703.html
標籤:电源外壳
