ProCrm.Xrm.PowerShell.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
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."
}