Functions/Query/New-CdsQueryExpression.ps1

<#
    .SYNOPSIS
    Initialize QueryExpression object instance.
#>

function New-CdsQueryExpression {
    [CmdletBinding()]
    [OutputType("Microsoft.Xrm.Sdk.Query.QueryExpression")]
    param
    (        
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]   
        [String]
        $LogicalName,

        [Parameter(Mandatory = $false)]
        [String[]]
        $Columns,
        
        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [int]
        $TopCount
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters); 
    }    
    process {
        $query = New-Object -TypeName "Microsoft.Xrm.Sdk.Query.QueryExpression" -ArgumentList $LogicalName;
        if ($Columns) {
            if ($Columns.Contains("*")) {
                $query.ColumnSet.AllColumns = $true;
            }
            else {
                $Columns | ForEach-Object {
                    $query.ColumnSet.AddColumn($_);
                }
            }
        }
        $query.NoLock = $true;
        if ($TopCount) {
            $query.TopCount = $TopCount;
        }
        $query;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function New-CdsQueryExpression -Alias *;

Register-ArgumentCompleter -CommandName New-CdsQueryExpression -ParameterName "LogicalName" -ScriptBlock {

    param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)

    $validLogicalNames = Get-CdsEntitiesLogicalName;
    return $validLogicalNames | Where-Object { $_ -like "*$wordToComplete*"};
}

Register-ArgumentCompleter -CommandName New-CdsQueryExpression -ParameterName "Columns" -ScriptBlock {

    param($CommandName, $ParameterName, $WordToComplete, $CommandAst, $FakeBoundParameters)

    if (-not ($fakeBoundParameters.ContainsKey("LogicalName"))) {
        return @();
    }

    $validAttributeNames = Get-CdsAttributesLogicalName -EntityLogicalName $fakeBoundParameters.LogicalName;
    return $validAttributeNames | Where-Object { $_ -like "*$wordToComplete*" };
}