Gizmo
Gizmo

Reputation: 3

How to filter a part of an output in powershell

I'm struggling with filtering the sessionId from the following output:

status  messages                           data
------  --------                           ----
Success {@{code=success; message=Success}} @{sessionId=0662c4d429bb51ef772e875f9c9b3a46; faSessionId=qfvio0382283ihbknhfh70kvn4; phpSessionId=qfvio0382283ihbknhfh70kvn4}

I've tried with the following:

$sessionId = $response | select "data"

This is returning:

data
----
@{sessionId=f77d5bfb5bdc65163e605d9c7edbcaed; faSessionId=hrsbd5iuq8i6dttfhimpm5baf1; phpSessionId=hrsbd5iuq8i6dttfhimpm5baf1}

I can't get it working to only extract the sessionId part.

It would be great if anyone could assist with the correct PowerShell code to obtain this.

Upvotes: 0

Views: 1247

Answers (1)

FoxDeploy
FoxDeploy

Reputation: 13567

It might help to think of the object you're working with like this, in JSON.

{
    "Status":  "Success",
    "Messages":  {
                     "code":  "success",
                     "message":  "Success"
                 },
    "Data":  {
                 "faSessionId":  "qfvio0382283ihbknhfh70kvn4",
                 "phpSessionId":  "qfvio0382283ihbknhfh70kvn4",
                 "sessionId":  "0662c4d429bb51ef772e875f9c9b3a46"
             }
}

You want the sessionId propeerty so you're selecting Data, but then you're finding that Data actually has those other properties of phpSessionId and faSessionId. Fortunately you have two approaches to get what you need.

Continue using the Select-Object cmdlet

You are already using this cmdlet but using the alias of Select, so you can keep using Select-Object to drill down all the way to the center of the Earth basically.

$response | Select-Object -ExpandProperty Data | Select-Object -ExpandProperty sessionId
>0662c4d429bb51ef772e875f9c9b3a46

Drill into the property you want with Dereferencing

This is the more programmery way to do it but is very popular. It's also called dot-notation.

$response.Data.sessionId
0662c4d429bb51ef772e875f9c9b3a46

Upvotes: 2

Related Questions