Functions/Security/Get-CdsRootBusinessUnit.ps1

<#
    .SYNOPSIS
    Retrieve root business unit
#>

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

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [String[]]
        $Columns = @("*")
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
       $queryBusinessUnit = New-CdsQueryExpression -LogicalName "businessunit" -Columns $Columns;
       $queryBusinessUnit = $queryBusinessUnit | Add-CdsQueryCondition -Field "parentbusinessunitid" -Condition Null;
       $businessUnits = $CdsClient | Get-CdsMultipleRecords -Query $queryBusinessUnit;
       $businessUnit = $businessUnits | Select-Object -First 1;
       $businessUnit;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}
Export-ModuleMember -Function Get-CdsRootBusinessUnit -Alias *;