Functions/Administration/Add-CdsAdministrationApp.ps1

<#
    .SYNOPSIS
    Add new App registration CDS with System Admin role.
#>

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

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

# $defaultBusinessUnitQuery = New-CdsQueryExpression -LogicalName businessunit -Columns parentbusinessunitid;
# $defaultBusinessUnitQuery = $defaultBusinessUnitQuery | Add-CdsQueryCondition -Field parentbusinessunitid -Condition Null;
# $defaultBusinessUnit = Get-CdsMultipleRecords -Query $defaultBusinessUnitQuery | Select-Object -First 1;
#
# $newUser = New-CdsEntity -LogicalName systemuser;
# $newUser | Set-CdsAttributeValue -Name domainname -Value "$AppDisplayName-application@dealfabric.com";
# $newUser | Set-CdsAttributeValue -Name internalemailaddress -Value "$AppDisplayName-application@dealfabric.com";
# $newUser | Set-CdsAttributeValue -Name firstname -Value "# Service";
# $newUser | Set-CdsAttributeValue -Name lastname -Value "$AppDisplayName App #";
# $newUser | Set-CdsAttributeValue -Name applicationid -Value ([Guid] $appId);
# $newUser | Set-CdsAttributeValue -Name applicationiduri -Value ([Guid] $appId);
# $newUser | Set-CdsAttributeValue -Name azureactivedirectoryobjectid -Value ([Guid] $app.ObjectId);
# $newUser | Set-CdsAttributeValue -Name businessunitid -Value $defaultBusinessUnit.ToEntityReference();
# $userId = $newUser | Add-CdsRecord;
#
# $roleRecord = Get-CdsRecord -LogicalName role -AttributeName name -Value "Administrateur système" -Columns parentrootroleid | ConvertTo-CdsObject;
# if(-not $roleRecord)
# {
# $roleRecord = Get-CdsRecord -LogicalName role -AttributeName name -Value "System administrator" -Columns parentrootroleid | ConvertTo-CdsObject;
# }
# $adminRoleReference = $roleRecord.parentrootroleid_value;
#
# $relationShip = New-Object -TypeName "Microsoft.Xrm.Sdk.Relationship" -ArgumentList "systemuserroles_association";
# $roleReferences = New-Object -TypeName "Microsoft.Xrm.Sdk.EntityReferenceCollection";
# $roleReferences.Add($adminRoleReference)
# try
# {
# $client.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-CdsAdministrationApp -Alias *;