How can I log only the ID of the folder named “Management” in PowerShell?

0
0
Asked By MellowPine42 On

I use Invoke-RestMethod to retrieve folder information from a container. The response.data property contains multiple folder objects, each with properties such as name, id, folder_type, and parent_id. I need to find the folder whose name is exactly "Management" and log only its ID. My current attempts either treat the entire collection as one object or return every folder ID instead of filtering by name. What is the correct PowerShell syntax for selecting the matching folder and retrieving its ID?

2 Answers

Answered By BrightHarbor7 On

Filter the folder objects first, then expand the id property. Since Invoke-RestMethod already converts the JSON into PowerShell objects, you do not need ConvertTo-Json for the lookup:

$managementIds = $response.data | Where-Object { $_.name -eq 'Management' } | Select-Object -ExpandProperty id

foreach ($id in $managementIds) {
LogWrite $id 'Result'
}

If there should only be one matching folder, you can log it directly:

$managementId = ($response.data | Where-Object { $_.name -eq 'Management' }).id
LogWrite $managementId 'Result'

The important distinction is that the filter must run against each object in $response.data. In the original attempt, $response.data.id is selected first, so the name property is no longer available for filtering.

QuietMaple18 -

Exactly—the $_ variable represents the current folder while Where-Object is iterating through the collection. Filtering $response.data.id cannot work because IDs do not have a name property.

Answered By SilverKite_63 On

You can also use the collection's Where() method, followed by the ID property:

$managementId = $response.data.Where({ $_.name -eq 'Management' }).id
LogWrite $managementId 'Result'

For a case-insensitive exact match, -eq is fine. If the API can return several folders named Management, this produces multiple IDs; otherwise it returns the single matching ID. There is no need to split the ID/name arrays—the sample response shows that each entry already contains both properties.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.