Search code examples
powershellkubectltext-parsing

Handling Data & Sorting Results in PowerShell


I am having trouble manipulating the data returned from a PowerShell query.

My goal is to get all NAMEs that are great than 30 days old (>30d).

After that, I want to load the NAMEs of these results into an array.

The data returned from my query is as follows:

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

Running a 'Select-Object' or 'Sort-Object' to filter the output doesn't work.

$output | Select-Object -Property NAME
$output | Sort-Object NAME

Solution

  • If $output is a single multiline string, you can do this:

    $result = ($output -split '\r?\n' -replace '\s+', ',' | ConvertFrom-Csv | Where-Object {[int]($_.Age -replace '\D') -gt 30}).NAME
    

    to get the Names in an array $result.

    If $output is already an array of strings, do:

    $result = ($output -replace '\s+', ',' | ConvertFrom-Csv | Where-Object {[int]($_.Age -replace '\D') -gt 30}).NAME