functions/azure/Get-ServicePrincipal.ps1
function Get-ServicePrincipal { param( [Parameter(Mandatory = $true, ParameterSetName = "ById")] [guid]$Id, [Parameter(Mandatory = $true, ParameterSetName = "ByAppId")] [guid]$AppId ) if ($PSCmdlet.ParameterSetName -eq "ById") { $uri = "https://graph.microsoft.com/v1.0/servicePrincipals/$Id" } else { $uri = "https://graph.microsoft.com/v1.0/servicePrincipals?`$filter=appId eq '$AppId'" } $headers = @{ Authorization = Get-RequestHeaderAuthorization -RequestUri $uri "Content-Type" = "application/json" } try { $response = Invoke-RestMethod -Method GET -Uri $uri -Headers $headers if ($PSCmdlet.ParameterSetName -eq "ById") { return $response } else { if ($response.value.Count -eq 0) { Write-Error "No service principal found with appId '$AppId'." return $null } if ($response.value.Count -gt 1) { Write-Warning "Multiple service principals found with appId '$AppId'!" } return $response.value[0] } } catch { Write-Error "Failed to retrieve service principal: $_" return $null } } |