Functions/Security/Get-CdsRoles.ps1

<#
    .SYNOPSIS
    Retrieve security roles
#>

function Get-CdsRoles {
    [CmdletBinding()]    
    [OutputType("Microsoft.Xrm.Sdk.Query.QueryExpression")]
    param
    ( 
        [Parameter(Mandatory=$false, ValueFromPipeline)]
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]
        $CdsClient = $Global:CdsClient,

        [Parameter(Mandatory=$false)]
        [Guid]
        $BusinessUnitId,

        [Parameter(Mandatory=$false)]
        [switch]
        $OnlyRoots = $false,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [String[]]
        $Columns = @("*"),

        # TODO : A faire une fois la méthode Get-CdsPrivileges implémentée
        [Parameter(Mandatory=$false)]
        [switch]
        $ExportPrivileges = $false
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
       $queryRoles = New-CdsQueryExpression -LogicalName "role" -Columns $Columns;
       if ($PSBoundParameters.ContainsKey('$BusinessUnitId'))
       {           
            $queryRoles = $queryRoles | Add-CdsQueryCondition -Field "businessunitid" -Condition Equal -Values "";
       }
       if($OnlyRoots)
       {           
            $parentBusinessUnit = Get-CdsRootBusinessUnit;
            $queryRoles = $queryRoles | Add-CdsQueryCondition -Field "businessunitid" -Condition Equal -Values  $parentBusinessUnit.Id;
       }
       $roles = $CdsClient | Get-CdsMultipleRecords -Query $queryRoles;
       $roles;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}
Export-ModuleMember -Function Get-CdsRoles -Alias *;