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
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.
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.

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.