ProCrm.Xrm.PowerShell.psm1

Function Add-XrmUserToSecurityRole(){
    
    param (
        
        [string]$loginname,
        [string]$rolename
    )

    Write-Output "Adding security role $rolename to user $loginname ..."
    Write-Output ""

    # Get users and roles
    $systemusers = Get-CrmRecords -EntityLogicalName SystemUser -FilterAttribute domainname -FilterOperator eq -FilterValue $loginname
    $securityroles = Get-CrmRecords -EntityLogicalName role -FilterAttribute name -FilterOperator eq -FilterValue $rolename

    # Get the recordIDs
    $systemuserid = $systemusers.CrmRecords[0].systemuserid
    $securityroleid = $securityroles.CrmRecords[0].roleid

    # Add the role
    Add-CrmSecurityRoleToUser -UserId $systemuserid -SecurityRoleId $securityroleid 
    # --> works only, if you have only one org. if there are orgs, then it finds more than one role
    
    Write-Output ""
    Write-Output "... security role added."
}

Function Get-XrmRecordsCount()
{
    param (
        $EntityNames
    )

    Write-Output "Counting records..."
    Write-Output ""

    foreach($entityName in $entityNames)
    {
        $count = Get-CrmEntityRecordCount -EntityLogicalName $entityName
        Write-Output "$count ${entityName}s found."
    }

    Write-Output ""
    Write-Output "... counting finished."
}
function Invoke-CrmConnectionInteractive() 
{ 
    # CREATE A CRM CONNECTION
    Connect-CrmOnlineDiscovery -InteractiveMode
}

function Invoke-CrmConnection()
{ 
    param(
        [System.Management.Automation.PSCredential]$CrmCredentials   ,
        [string]$CrmServerUrl     
    )

    # CREATE A CRM CONNECTION
    Connect-CrmOnline -Credential $CrmCredentials -ServerUrl $CrmServerUrl 
}

function Get-Credentials()
{
    param(
        [string]$Username,
        [securestring]$Password      
    )

    return New-Object System.Management.Automation.PSCredential ($Username, $Password)
}
function New-XrmPublisherAndDefaultSolution() 
{    
    param (   
        [string]$PublisherName,
        [string]$PublisherLogicalName,
        [string]$PublisherPrefix,
        [string]$SolutionName,
        [string]$SolutionLogicalName
    )

    Write-Output "Creating solution and publisher ..."
    Write-Output ""

    # CREATE Publisher
    $publishers = Get-CrmRecords -EntityLogicalName publisher -FilterAttribute uniquename -FilterOperator eq -FilterValue $PublisherLogicalName
    
    if($publishers.Count -eq 0)
    {
        $publisherid = New-CrmRecord -EntityLogicalName publisher -Fields @{"uniquename"=$PublisherLogicalName;"friendlyname"=$PublisherName;"customizationprefix"=$PublisherPrefix}
    }
    else
    {
        $publisherid = $publishers.CrmRecords[0].publisherid    
    }

    Write-Output "Publisher with id = $publisherid found or created ..."

    # CREATE SOLUTION
    $publisherref = New-CrmEntityReference -EntityLogicalName publisher -Id $publisherid

    $solutionid = New-CrmRecord -EntityLogicalName solution -Fields @{"uniquename"=$SolutionLogicalName;"friendlyname"=$SolutionName;"publisherid"=$publisherref;"version"="1.0.0.0"}

    Write-Output ""
    Write-Output "... solution created ($solutionid)."

    return $solutionid
}

Function Invoke-XrmSolutionVersionIncremention()
{
    params(
        [string]$SolutionName
    )

    $solutions = Get-CrmRecords -EntityLogicalName solution -FilterAttribute uniquename -FilterOperator eq -FilterValue $SolutionName -Fields uniquename,version,ismanaged
        
    $solution = $solutions.CrmRecords[0]
    $currentVersion = $solution.version
    
    $positionIndexOfLastDot = $currentVersion.LastIndexOf('.')
    $currentVersionLastNumber = [convert]::ToInt32($currentVersion.Substring($positionIndexOfLastDot+1,$currentVersion.Length-$positionIndexOfLastDot-1))
    $solution.version = ($solution.version.SubString(0,$positionIndexOfLastDot+1))+($currentVersionLastNumber + 1).ToString()
    
    Set-CrmRecord -CrmRecord $solution
    
    Write-Output Version number of solution $solutionname updated to $solution.version
}
Function Import-XrmSolution(){

    param (
        
        [string]$solutionPath
    )

    Try{
        Write-Output "Importing solution ..."
        Write-Output ""

        Import-CrmSolution -SolutionFilePath $solutionPath -ActivatePlugIns $true -MaxWaitTimeInSeconds 12000

        Write-Output ""
        Write-Output "... solution imported."

    }Catch
    {
        Write-Output "Error $_.Exception.Message"
        $_.Exception.InnerException.Message
    }
}

Function Export-XrmSolution(){

    param (
        
        [string]$solutionName,
        [string]$solutionPath
    )

    Try{
        Write-Output "Exporting solution ..."
        Write-Output ""

        Export-CrmSolution -SolutionName:$solutionname -SolutionZipFileName:$solutionname'_Managed.zip' -SolutionFilePath:$solutionPath -Managed:$true
        Invoke-XrmSolutionVersionIncremention -solutionname $solutionname

        Write-Output ""
        Write-Output "... solution exported."

    }Catch
    {
        Write-Output "Error $_.Exception.Message"
        $_.Exception.InnerException.Message
    }
}

Function Remove-XrmSolution(){

    param (
        
        [string]$solutionName
    )
    
    Write-Output "Deleting solution ..."
    Write-Output ""
    
    $solutions = Get-CrmRecords -EntityLogicalName solution -FilterAttribute uniquename -FilterOperator eq -FilterValue $solutionName -Fields uniquename,version,ismanaged
    $solution = $solutions.CrmRecords[0]

    Remove-CrmRecord -CrmRecord $solution
    
    Write-Output ""
    Write-Output "... solution deleted."
}

function Invoke-XrmWorkflow () {
    
    param (
        
        [string]$viewName,
        [string]$WorkflowName
    )

    Write-Output "Starting workflows ..."
    Write-Output ""
    
    $crmrecords  = Get-CrmRecordsByViewName -ViewName $viewName

    Write-Output "Found $crmrecords.Count to execute the workflow ..."

    foreach ($crmrecord in $crmrecords.CrmRecords) 
    {   
        Invoke-CrmRecordWorkflow -CrmRecord $crmrecord -WorkflowName $WorkflowName
    }
    
    Write-Output ""
    Write-Output "... workflow execution finished."
}function Export-AllCrmSolutionDataToCsv()
{
    param(
        [string]$CsvPath
    )

    Write-Host "Getting solutions and creating CSV file ..."
    Write-Host ""

    $solutions = Get-CrmRecords -EntityLogicalName solution -Fields uniquename,friendlyname,ismanaged
    
    Add-Content -Path $CsvPath -Value "DisyplayName;UniqueName;IsManaged"

    foreach($solution in $solutions.CrmRecords)
    {
        $uname = $solution.uniquename
        $disname = $solution.friendlyname
        $ismanaged = $solution.ismanaged.ToString()

        Write-Host "$disname;$uname;$ismanaged"
        Add-Content -Path $CsvPath  -Value "$disname;$uname;$ismanaged"
    }

    Write-Host ""
    Write-Host "Finished getting and exporting solution data."
}

function New-CrmAutonumberAttribute () {
    
    param (   
        [string]$AttributeName,
        [string]$AttributeDisplayname,
        [string]$EntitySchemaname,
        [string]$AutoNumberFormat
    )

    Write-Output "Creating autonumber attribute $AttributeName ..."
    Write-Output ""

    $autonumattribute = New-Object Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata
    $autonumattribute.SchemaName = $AttributeName
    $autonumattribute.LogicalName = $AttributeName
    $autonumattribute.DisplayName = New-Object Microsoft.Xrm.Sdk.Label($attributedisplayname,1033)
    $autonumattribute.Format = [Microsoft.Xrm.Sdk.Metadata.StringFormat]::Text
    $autonumattribute.MaxLength = 100
    $autonumattribute.AutoNumberFormat = $AutoNumberFormat

    $request = New-Object Microsoft.Xrm.Sdk.Messages.CreateAttributeRequest
    $request.Attribute = $autonumattribute
    $request.EntityName = $EntitySchemaname

    $response = $conn.Execute($request)

    Write-Output ""
    Write-Output "... autonumber attribute $AttributeName created."
    
    return $response
}

function New-CrmEntity() {

    param (   
        [string]$EntityName,
        [string]$EntitySchemaName,
        [string]$EntityPrefix
    )
    
    Write-Output "Creating new entity $EntityName ..."
    Write-Output ""

    $newentity = New-Object Microsoft.Xrm.Sdk.Metadata.EntityMetadata
    $newentity.SchemaName = $EntityPrefix+"_"+$EntitySchemaName
    $newentity.DisplayName = New-Object Microsoft.Xrm.Sdk.Label($EntityName, 1033)
    $newentity.DisplayCollectionName = New-Object Microsoft.Xrm.Sdk.Label($($EntityName + 's'),1033)
    $newentity.OwnershipType = [Microsoft.Xrm.Sdk.Metadata.OwnershipTypes]::UserOwned
    $newentity.IsActivity = $false

    $primattribute = New-Object Microsoft.Xrm.Sdk.Metadata.StringAttributeMetadata
    $primattribute.SchemaName = $EntityPrefix+"_name"
    $primattribute.DisplayName = New-Object Microsoft.Xrm.Sdk.Label("Name",1033)
    $primattribute.Format = [Microsoft.Xrm.Sdk.Metadata.StringFormat]::Text
    $primattribute.MaxLength = 100

    $request = New-Object Microsoft.Xrm.Sdk.Messages.CreateEntityRequest
    $request.Entity = $newentity
    $request.PrimaryAttribute = $primattribute

    $response = $conn.Execute($request)
   
    Write-Output ""
    Write-Output "... entity $EntityName created."

    return $response
}

function Remove-CrmEntity () {
    
    param (
        
        [string]$EntityLogicalName
    )
    
    Write-Output "Deleting entity ..."
    Write-Output ""
    
    # TODO
    
    Write-Output ""
    Write-Output "... entity deleted."
}