James Dunn
James Dunn

Reputation: 35

Accessing nested objects in PowerShell

I am trying to extract specific values from a PowerShell object to create a CSV to use in another application. More specifically I have used the Microsoft Graph API to download events in a calendar over a set time frame.

I have used this command in PowerShell to get the initial data

$data = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/{username}/calendar/events?startDateTime=2019-01-01T00:00:00.0000000&endDateTime=2019-01-30T23:59:00.0000000&select=subject,start,end,IsAllDay,ResponseStatus"

From here I can access each item in the $data variable to get a nice list of events.

$data |
    ForEach-Object {$_.value} |
    Select -Property subject, start, end, IsAllDay, ResponseStatus

Output:

subject        : Event today
start          : @{dateTime=2019-01-18T11:00:00.0000000; timeZone=GMT Standard Time}
end            : @{dateTime=2019-01-18T11:30:00.0000000; timeZone=GMT Standard Time}
isAllDay       : False
responseStatus : @{response=none; time=0001-01-01T00:00:00Z}

subject        : Event tomorrow
start          : @{dateTime=2019-01-18T09:45:00.0000000; timeZone=GMT Standard Time}
end            : @{dateTime=2019-01-18T12:15:00.0000000; timeZone=GMT Standard Time}
isAllDay       : False
responseStatus : @{response=none; time=0001-01-01T00:00:00Z}

What I would like is to select the dateTime data in start and end objects so it looks like this:

subject        : Event today
start          : 2019-01-18T11:00:00.0000000
end            : 2019-01-18T11:30:00.0000000
isAllDay       : False
responseStatus : @{response=none; time=0001-01-01T00:00:00Z}

subject        : Event tomorrow
start          : 2019-01-18T09:45:00.0000000
end            : 2019-01-18T12:15:00.0000000
isAllDay       : False
responseStatus : @{response=none; time=0001-01-01T00:00:00Z}

I can do this in the PowerShell window with the command

$data.value.[0].start.dateTime

but how can I do this with the select command above?

Upvotes: 3

Views: 10394

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200573

Use calculated properties for expanding properties of the nested objects:

$data |
    Select-Object -Expand value |
    Select-Object subject, @{n='start';e={$_.start.dateTime}},
        @{n='end';e={$_.end.dateTime}}, IsAllDay, ResponseStatus

Upvotes: 4

Related Questions