我在處理 PowerShell 查詢回傳的資料時遇到問題。
我的目標是獲得超過 30 天(> 30 天)的所有 NAME。
之后,我想將這些結果的 NAME 加載到一個陣列中。
我的查詢回傳的資料如下:
PS C:\Users\> $output
NAME STATUS AGE
dread-gorge Active 284d
dread-lagoon Active 210d
carncier-basin Active 164d
chantague-shallows Active 164d
hilraine-loch Active 311d
stangrave-waters Active 271d
運行“選擇物件”或“排序物件”來過濾輸出不起作用。
$output | Select-Object -Property NAME
$output | Sort-Object NAME
uj5u.com熱心網友回復:
如果$output是單個多行字串,您可以這樣做:
$result = ($output -split '\r?\n' -replace '\s ', ',' | ConvertFrom-Csv | Where-Object {[int]($_.Age -replace '\D') -gt 30}).NAME
獲取陣列中的名稱$result。
如果$output已經是一個字串陣列,請執行以下操作:
$result = ($output -replace '\s ', ',' | ConvertFrom-Csv | Where-Object {[int]($_.Age -replace '\D') -gt 30}).NAME
uj5u.com熱心網友回復:
更新:
有關將輸入轉換為 CSV 格式并使用 對其進行決議的高級解決方案
ConvertFrom-Csv,請參閱Theo 的回答。下面的解決方案可能對其文本決議技術感興趣。
正如評論所指出的,通常最好讓外部程式發出結構化文本,例如 JSON,因為決議顯示格式的文本本質上是脆弱的。
根據kubectldocs,您可以使用它-o json來實作(正如 Mathias 也指出的)。
如果資料足夠簡單以至于純文本決議仍然是一種選擇,您可以嘗試以下操作,它依賴于運算-split符的一元形式將每一行分解為欄位:
# Sample output from kubectl.
# Note: Capturing output from an external programs such as kubectl
# results in an *array of lines*.
# The -split '\r?\n` operation splits the multiline here-string into
# just that.
$kubeCtlOutput = @'
NAME STATUS AGE
dread-gorge Active 28d
dread-lagoon Active 31d
carncier-basin Active 16d
chantague-shallows Active 164d
'@ -split '\r?\n'
# Process the array's lines.
[array] $namesOfInterest =
$kubeCtlOutput |
Select-Object -Skip 1 |
ForEach-Object {
$name, $age = (-split $_)[0, -1]
if ([int] ($age -replace '\D') -gt 30) {
$name
}
}
$namesOfInterest # Print the result.
輸出,顯示只提取了AGE大于30天的兩行的名稱:
dread-lagoon
chantague-shallows
這個相關問題的答案定義了可以將列狀純文本資料決議為物件的通用輔助函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/363106.html
上一篇:配置更新-PowerShell
