Public/Get-IAMCoreOrgUnit.ps1

<#
.SYNOPSIS
    Gets CoreOrgUnit objects from the IAM Core API.

.DESCRIPTION
    This function retrieves CoreOrgUnit objects from the IAM Core API.

.EXAMPLE
    Get-IAMCoreOrgUnit
#>

function Get-IAMCoreOrgUnit {
    [CmdletBinding(DefaultParameterSetName = "Default")]
    param (
        [Parameter(Mandatory = $false, ParameterSetName = "Default")]
        [int] $PageSize = 10000,

        [Parameter(Mandatory = $true, ParameterSetName = "Single", ValueFromPipelineByPropertyName = $true, ValueFromPipeline = $true)]
        [ValidatePattern("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", ErrorMessage = "Id must be a valid GUID.")] # Is a guid connector object id
        [string] $Id,

        [Parameter(Mandatory = $false, ParameterSetName = "Single")]
        [Boolean] $IncludeParents = $false
    )

    begin {
        $Script:IdsToFetch = @()
    }

    process {
        if ($PSCmdlet.ParameterSetName -eq "Single") {
            $Script:IdsToFetch += $Id
        }
        else {
            Get-IAMCoreObject -ObjectType "CoreOrgUnit" -PageSize $PageSize
        }
    }
    
    end {
        if ($Script:IdsToFetch -and $Script:IdsToFetch.Count -gt 0) {
            $Buckets = $Script:IdsToFetch | Get-IAMCoreBucket
            $Buckets.GetEnumerator() | ForEach-Object {
                Write-Verbose "Processing bucket $($_.Key) with $($_.Value.Count) org unit IDs"
                $Body = @{ 
                    ids            = $_.Value 
                    includeParents = $IncludeParents
                }

                $StatusCode = 0
                $Result = Invoke-RestMethod -Uri "$Script:APIRoot/sync/coreobjects/orgunits/multiple" -Headers (Get-IAMCoreHeader) -Method Post -ContentType "application/json" -Body ($Body | ConvertTo-Json -Depth 10) -SkipHttpErrorCheck -StatusCodeVariable StatusCode

                if ($StatusCode -eq 200) {
                    $Result.Data
                }
                else {
                    if ($Result.Errors) {
                        throw "Failed to get IAM Core org units: $($Result.Errors -join ', ')"
                    }
                    elseif ($StatusCode -eq 403) {
                        throw "Access denied"
                    }
                    else {
                        throw "Failed to get IAM Core org units (Status code: $StatusCode)"
                    }
                }
            }
        }
    }
}