Public/Get-InforcerUser.ps1
|
function Get-InforcerUser { <# .SYNOPSIS Retrieves users from an Inforcer tenant. Required API scope(s): Tenants.Users.Read + Tenants.Read (only when -TenantId is a GUID or tenant name) (API key); User & Group Management + Tenants (only for a tenant name) permission (API client, unconfirmed). -IncludeAuthenticationMethods and -IncludeMailbox need a login with an API client. .DESCRIPTION Gets a list of users or a single user by ID from the Inforcer API. Works with both login types (API key and client credentials). When called without -UserId, returns all users (UserSummary objects) with optional search filtering and auto-pagination. When called with -UserId, returns the full user detail (User object) including groups, roles, devices, and risk information. .PARAMETER Format Output format. Currently only 'Raw' is supported. .PARAMETER TenantId The Inforcer tenant ID. Accepts numeric ID (API-key login only), Microsoft tenant GUID, or tenant name. Supports pipeline input. .PARAMETER Search Server-side search filter for the user list. Only available in the List parameter set. .PARAMETER MaxResults Maximum number of users to return. 0 (default) means no limit. Only available in the List parameter set. .PARAMETER UserId The user ID (GUID) to retrieve full details for. Only available in the ById parameter set. .PARAMETER IncludeAuthenticationMethods Adds authenticationMethods to the user: the sign-in methods they have registered, such as their password, phones, Microsoft Authenticator and passkeys (one extra request). Passwords and Temporary Access Pass codes are never returned. Only with -UserId and a login with an API client (Connect-Inforcer -ClientId -ClientSecret); an API-key login gets the error RequiresApiClient. .PARAMETER IncludeMailbox Adds mailbox to the user: the Exchange Online mailbox as it is now (type, size, archive, litigation hold, email addresses, hiddenFromAddressList, forwarding, mailApps), with autoReply, permissions (and unreadPermissions, the kinds Exchange could not read just now), calendarAccess, mailGroups (distribution lists and mail-enabled security groups) and inboxRules. Six extra requests. mailbox is null when the user has no mailbox. A mailbox Exchange took offline (no licence with Exchange Online) gives the error 'Mailbox offline' and leaves mailbox out. Only with -UserId and a login with an API client. Change these with Set-InforcerUser. .PARAMETER OutputType Output type: 'PowerShellObject' (default) or 'JsonObject'. Depth 100; the v1 list is always a JSON array. Piped tenants: each user carries TenantId and JsonObject returns one array for all tenants. .EXAMPLE Get-InforcerUser -TenantId 'Contoso' Lists all users in the tenant Contoso. .EXAMPLE Get-InforcerUser -TenantId 'Contoso' -Search "Adele" Searches for users matching "Adele" in the tenant Contoso. .EXAMPLE Get-InforcerUser -TenantId 'Contoso' -UserId "00000000-0000-0000-0000-000000000005" Gets full detail for a specific user. .EXAMPLE (Get-InforcerUser -TenantId 'Contoso' -UserId "00000000-0000-0000-0000-000000000005" -IncludeAuthenticationMethods).authenticationMethods Lists the sign-in methods the user has registered, such as password, phone and passkey. .EXAMPLE $mailbox = (Get-InforcerUser -TenantId 'Contoso' -UserId "00000000-0000-0000-0000-000000000005" -IncludeMailbox).mailbox $mailbox.forwarding; $mailbox.inboxRules | Where-Object forwardsExternally Shows where the user's mail is forwarded and which inbox rules send mail outside the tenant. .EXAMPLE Get-InforcerTenant -TenantId 'Contoso' | Get-InforcerUser Lists all users in the piped tenant. .EXAMPLE Get-InforcerUser -TenantId 'Contoso' -OutputType JsonObject Returns the users as a JSON string (depth 100) instead of objects. .OUTPUTS PSObject or String (when -OutputType JsonObject) .LINK https://github.com/royklo/InforcerCommunity/blob/main/docs/CMDLET-REFERENCE.md#get-inforceruser .LINK Connect-Inforcer #> [CmdletBinding(DefaultParameterSetName = 'List')] [OutputType([PSObject], [string])] param( [Parameter(ParameterSetName = 'List')] [Parameter(ParameterSetName = 'ById')] [ValidateSet('Raw')] [string]$Format = 'Raw', [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'List')] [Parameter(Mandatory, ValueFromPipelineByPropertyName, ParameterSetName = 'ById')] [Alias('ClientTenantId', 'MsTenantId')] [object]$TenantId, [Parameter(ParameterSetName = 'List')] [string]$Search, [Parameter(ParameterSetName = 'List')] [int]$MaxResults = 0, [Parameter(Mandatory, ParameterSetName = 'ById')] [string]$UserId, [Parameter(ParameterSetName = 'ById')] [switch]$IncludeAuthenticationMethods, [Parameter(ParameterSetName = 'ById')] [switch]$IncludeMailbox, [Parameter(ParameterSetName = 'List')] [Parameter(ParameterSetName = 'ById')] [ValidateSet('PowerShellObject', 'JsonObject')] [string]$OutputType = 'PowerShellObject' ) begin { $pipedJson = [System.Collections.Generic.List[object]]::new() } process { if (-not (Test-InforcerSession)) { Write-Error -Message "Not connected to Inforcer. Use Connect-Inforcer first." -ErrorId 'NotConnected' -Category ConnectionError return } if (($IncludeAuthenticationMethods -or $IncludeMailbox) -and $script:InforcerSession.ApiVersion -ne 'v1') { Write-Error -Message 'Authentication methods and mailboxes need a login with an API client (Connect-Inforcer -ClientId -ClientSecret). The API-key (beta) API does not return them.' -ErrorId 'RequiresApiClient' -Category InvalidOperation return } try { $resolvedTenantId = Resolve-InforcerTenantId -TenantId $TenantId } catch { Write-Error -Message $_.Exception.Message -ErrorId 'InvalidTenantId' -Category InvalidArgument return } $piped = $PSCmdlet.MyInvocation.ExpectingInput $addTenantId = { param($item) if ($piped -and $item -is [PSObject] -and -not $item.PSObject.Properties['TenantId']) { $item.PSObject.Properties.Add([System.Management.Automation.PSNoteProperty]::new('TenantId', $resolvedTenantId)) } } if ($PSCmdlet.ParameterSetName -eq 'ById') { # --- ById: single user detail --- $endpoint = "/tenants/$resolvedTenantId/users/$([System.Uri]::EscapeDataString($UserId))" $err = $null # -PreserveStructure: user detail response is a single object with many nested arrays # (groups, roles, devices, appRoleAssignments, assignedLicenses, businessPhones, ...). # Without it, Invoke-InforcerApiRequest would unwrap to the first array property. $response = Invoke-InforcerApiRequest -Endpoint $endpoint -Method GET -OutputType PowerShellObject -PreserveStructure -ObjectType User -ErrorVariable err -ErrorAction SilentlyContinue if ($null -eq $response) { if (-not $err -or $err[-1].FullyQualifiedErrorId -like 'ApiRequestFailed_404*') { Write-Error -Message "User '$UserId' not found in tenant '$resolvedTenantId'." -ErrorId 'UserNotFound' -Category ObjectNotFound } else { Write-Error -ErrorRecord $err[-1] } return } if ($IncludeAuthenticationMethods) { $methods = Invoke-InforcerApiRequest -Endpoint "$endpoint/authenticationMethods" -Method GET -PreserveStructure if ($null -ne $methods) { $response.PSObject.Properties.Remove('authenticationMethods') $response.PSObject.Properties.Add([System.Management.Automation.PSNoteProperty]::new('authenticationMethods', @($methods.authenticationMethods))) } } if ($IncludeMailbox) { $mailboxErr = $null $mailbox = Invoke-InforcerApiRequest -Endpoint "$endpoint/mailbox" -Method GET -PreserveStructure -ErrorVariable mailboxErr -ErrorAction SilentlyContinue # 404: the user has no mailbox, so mailbox is null; any other failure is reported and leaves mailbox out. $noMailbox = $mailboxErr -and $mailboxErr[-1].FullyQualifiedErrorId -like 'ApiRequestFailed_404*' if ($mailboxErr -and -not $noMailbox) { Write-Error -ErrorRecord $mailboxErr[-1] } if ($null -ne $mailbox) { foreach ($part in 'autoReply', 'permissions', 'calendarAccess', 'mailGroups', 'inboxRules') { $result = Invoke-InforcerApiRequest -Endpoint "$endpoint/mailbox/$part" -Method GET -PreserveStructure if ($null -eq $result) { continue } # Plain assignments: an if-expression would unroll an empty list to null. $value = $result if ($part -ne 'autoReply') { $value = @($result.$part) } $mailbox | Add-Member -NotePropertyName $part -NotePropertyValue $value -Force if ($part -eq 'permissions') { $mailbox | Add-Member -NotePropertyName unreadPermissions -NotePropertyValue @($result.unreadPermissions) -Force } } } if (-not $mailboxErr -or $noMailbox) { $response | Add-Member -NotePropertyName mailbox -NotePropertyValue $mailbox -Force } } & $addTenantId $response if ($OutputType -eq 'JsonObject') { if ($piped) { $pipedJson.Add($response); return } return $response | ConvertTo-Json -Depth 100 } $null = Add-InforcerPropertyAliases -InputObject $response -ObjectType User $response.PSObject.TypeNames.Insert(0, 'InforcerCommunity.User') return $response } # --- List: paginated user list --- $endpoint = "/tenants/$resolvedTenantId/users" if ($Search) { $endpoint += '?search=' + [System.Uri]::EscapeDataString($Search) } if ($OutputType -eq 'JsonObject') { $users = @(Invoke-InforcerPagedRequest -Endpoint $endpoint -ObjectType User -MaxResults $MaxResults -ErrorVariable listErr) if ($listErr) { return } if ($piped) { foreach ($u in $users) { & $addTenantId $u; $pipedJson.Add($u) }; return } if ($script:InforcerSession.ApiVersion -eq 'v1') { return ConvertTo-Json -InputObject $users -Depth 100 } return $users | ConvertTo-Json -Depth 100 } Invoke-InforcerPagedRequest -Endpoint $endpoint -ObjectType User -MaxResults $MaxResults | ForEach-Object { & $addTenantId $_ $null = Add-InforcerPropertyAliases -InputObject $_ -ObjectType UserSummary $_.PSObject.TypeNames.Insert(0, 'InforcerCommunity.UserSummary') $_ } } end { if ($PSCmdlet.MyInvocation.ExpectingInput -and $OutputType -eq 'JsonObject' -and (Test-InforcerSession)) { ConvertTo-Json -InputObject @($pipedJson) -Depth 100 } } } |