Functions/Security/Add-CdsUserRoles.ps1

<#
    .SYNOPSIS
   Add security roles to user
#>

function Add-CdsUserRoles {
    [CmdletBinding()]    
    param
    (        
        [Parameter(Mandatory=$false, ValueFromPipeline)]
        [Microsoft.Xrm.Tooling.Connector.CrmServiceClient]
        $CdsClient = $Global:CdsClient,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [Guid]
        $UserId,

        [Parameter(Mandatory = $true)]
        [Guid[]]
        $Roles = @()
    )
    begin {
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);       
    }    
    process {
        $relationShip = New-Object -TypeName "Microsoft.Xrm.Sdk.Relationship" -ArgumentList "systemuserroles_association";
        $roleReferences = New-Object -TypeName "Microsoft.Xrm.Sdk.EntityReferenceCollection";
        $Roles | ForEach-Object {
            $roleReference = New-CdsEntityReference -LogicalName "role" -Id $_;
            $roleReferences.Add($roleReference);
        }
        try
        {
            $CdsClient.Associate("systemuser", $UserId, $relationShip, $roleReferences);
        }
        catch
        {
            if(-not $_.Exception.Message.Contains("Cannot insert duplicate key"))
            {
                throw $_.Exception;
            }
        }
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}
Export-ModuleMember -Function Add-CdsUserRoles -Alias *;