Update:
For a superior solution that transforms the input into CSV format and parses it with ConvertFrom-Csv
, see Theo's answer.
The solution below may be of interest for its text-parsing techniques.
As the comments note, it's generally better to make an external program emit structured text, such as JSON, because parsing for-display formatted text is inherently brittle.
According to the kubectl
docs, you can use -o json
to achieve that (as Mathias has also noted).
If the data is simple enough so that plain-text parsing is still an option, you can try the following, which relies on the unary form of the -split
operator to break each line into fields:
# 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.
Output, showing that only the names of the two lines whose AGE
is greater than 30
days were extracted:
dread-lagoon
chantague-shallows
This related question has answers that define generic helper functions that can parse columnar plain-text data into objects.