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

0
1
Asked By MellowCedar42 On

I'm using Invoke-RestMethod to retrieve folder objects from a container. Each item includes 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 unique ID. Although the response contains several folders, my current attempts log every folder ID instead of just the matching one. What is the correct way to filter the response and retrieve the ID?

2 Answers

Answered By BrightOwl_73 On

Filter the folder objects first, then expand the id property. The filter must run against each item in $response.data, not against the array of IDs:

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

LogWrite ($managementId | ConvertTo-Json).Replace('\n','n') 'Result'

If there can be multiple folders with that name, $managementId will contain multiple IDs. To process each one, use:

$response.data | Where-Object { $_.name -eq 'Management' } | ForEach-Object {
LogWrite ($_.id | ConvertTo-Json).Replace('\n','n') 'Result'
}

The important distinction is using $_, which represents the current folder being evaluated. In the original attempts, $response.data.name refers to the entire collection, so the filtering condition is not applied item by item.

QuietMaple19 -

This also works with the simplified syntax: $response.data.Where({ $_.name -eq 'Management' }).id. If only one match is expected, you can assign that result directly to a variable.

Answered By SilverMango_8 On

Invoke-RestMethod already converts JSON into PowerShell objects, so you do not need to convert the response to JSON before filtering it. Assuming the API response has the structure shown, this is enough:

$folderId = ($response.data | Where-Object Name -EQ 'Management').id

You can then pass $folderId to the next operation. ConvertTo-Json is only useful when you specifically need to format the value for logging or another JSON-based request.

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.