Home > Software engineering >  Powershell iterate System.Object
Powershell iterate System.Object

Time:04-16

I am using OpenShift CLI in a PowerShell Script,

I have a variable $ProjectList with Data. Not sure of its datatype, but doing $ProjectsList.GetType() gives me below

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Looking for a way to Get Name field whose status is running

NAME                                             READY   STATUS             AGE
Service One                                     0/1     Completed            13d
Service Two                                     0/1     Running              13d
Service 3                                       0/1     Running              13d
Service 4                                       0/1     Completed            13d

$ProjectList.Length give me the value 5.

I am looking for a way to get the Name whole status is Running. Tried below code but it does not work.

$ProjectsList = c:\TEMP\oc.exe get pods
$FilteredList = $ProjectList.Where{ $_.STATUS -eq 'Running' }

write-host $FilteredList //This shows empty

Can you help me with some pseudo code.

CodePudding user response:

Your query does not work because the CLI outputs table format by default. So your $ProjectList just contains the formatted text output as an array of strings, which PowerShell does not understand.

According to the docs, the CLI is able to output JSON format, by passing argument -o json. This can easily be parsed into actual objects by using PowerShell's ConvertFrom-Json cmdlet:

$ProjectsList = c:\TEMP\oc.exe get pods -o json | Out-String | ConvertFrom-Json

$FilteredList = $ProjectList.Where{ $_.STATUS -eq 'Running' }

The Out-String call is there because ConvertFrom-Json works best (most predictably1) when given a single input string. When redirecting the output of a native process, you would normally get each line one-by-one, as a separate string. Using Out-String makes sure that the next command in the pipeline receives the output as a single multiline string instead.

1) See this answer for pitfalls when passing multiple strings to ConvertFrom-Json.

  • Related