src/Security/Get-XrmWhoAmI.ps1

<#
    .SYNOPSIS
    Retrieve current user id.

    .DESCRIPTION
    Get system user unique identifier.

    .PARAMETER XrmClient
    Xrm connector initialized to target instance. Use latest one by default. (Dataverse ServiceClient)

    .OUTPUTS
    System.Guid. Id of the system user the connector is signed in as.

    .EXAMPLE
    $xrmClient = New-XrmClient -ConnectionString $connectionString;
    $userId = $xrmClient | Get-XrmWhoAmI;
    $roles = $xrmClient | Get-XrmUserRoles -UserId $userId -Columns "name";

    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Get-XrmWhoAmI.md
#>

function Get-XrmWhoAmI {
    [CmdletBinding()]
    [OutputType([System.Guid])]
    param
    ( 
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        [Microsoft.PowerPlatform.Dataverse.Client.ServiceClient]
        $XrmClient = $Global:XrmClient        
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
    
        $request = new-xrmrequest -Name "WhoAmI";
        $response = Invoke-xrmRequest -XrmClient $XrmClient -Request $request;

        $userId = $response.Results["UserId"].Guid;
        $userId;
    }
    end {
        $StopWatch.Stop();
        Trace-XrmFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}
Export-ModuleMember -Function Get-XrmWhoAmI -Alias *;