Functions/Query/Add-CdsQueryLink.ps1

<#
    .SYNOPSIS
    Add link entity to given query expression
#>

function Add-CdsQueryLink {
    [CmdletBinding()]
    [OutputType("Microsoft.Xrm.Sdk.Query.LinkEntity")]
    param
    (        
        [Parameter(Mandatory = $true, ValueFromPipeline)]
        [ValidateNotNullOrEmpty()]
        [Microsoft.Xrm.Sdk.Query.QueryExpression]
        $Query,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $FromAttributeName,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ToEntityName,

        [Parameter(Mandatory = $false)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ToAttributeName
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {

        $link = $Query.AddLink($ToEntityName, $FromAttributeName, $ToAttributeName);
        $link;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Add-CdsQueryLink -Alias *;

Register-ArgumentCompleter -CommandName Add-CdsQueryLink -ParameterName "FromAttributeName" -ScriptBlock {

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

    # TODO : Search query in pipeline
    if (-not ($fakeBoundParameters.ContainsKey("Query"))) {
        return @();
    }

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

Register-ArgumentCompleter -CommandName Add-CdsQueryLink -ParameterName "ToEntityName" -ScriptBlock {

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

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

Register-ArgumentCompleter -CommandName Add-CdsQueryLink -ParameterName "ToAttributeName" -ScriptBlock {

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

    # TODO : Search query in pipeline
    if (-not ($fakeBoundParameters.ContainsKey("ToEntityName"))) {
        return @();
    }

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