Private/Get-GroupByName.ps1
|
function Get-GroupByName { <# .SYNOPSIS Retrieves Entra ID groups by display name. .DESCRIPTION Looks up groups in Microsoft Graph whose display name exactly matches the given name (case-insensitive). With -StartsWith, returns groups whose display name begins with the given text instead. Group display names are not unique in Entra ID, so this can return more than one group. Returns an empty array if none are found. #> param( [Parameter(Mandatory)] [string]$Name, [switch]$StartsWith, [int]$Top = 25 ) # Escape single quotes for OData, then URL-encode the whole filter expression # so names containing characters like '&', '#' or '+' are passed through intact $escapedName = $Name.Replace("'", "''") $filter = if ($StartsWith) { "startswith(displayName,'$escapedName')" } else { "displayName eq '$escapedName'" } $uri = "$script:GraphBaseUrl/groups?`$select=id,displayName,description,membershipRule,groupTypes,securityEnabled&`$filter=$([uri]::EscapeDataString($filter))&`$top=$Top" try { $response = Invoke-Graph -Uri $uri } catch { return @() } $groups = @($response.value) foreach ($group in $groups) { $groupType = if ($group.membershipRule) { "Dynamic" } else { "Assigned" } $group | Add-Member -NotePropertyName "GroupType" -NotePropertyValue $groupType -Force } # Graph returns hashtables, which Windows PowerShell 5.1 can't sort by property # name - use scriptblocks. Sort by id too so same-named groups list in a stable order. return @($groups | Sort-Object { $_.displayName }, { $_.id }) } |