-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBuildCustomFunctions.ps1
644 lines (640 loc) · 33.3 KB
/
BuildCustomFunctions.ps1
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
#Requires -Modules powershell-yaml
Param(
[Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = 'Path to SDK config file.')][ValidateNotNullOrEmpty()][System.String[]]$ConfigPath
, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = 'Path to SDK module manifest.')][ValidateNotNullOrEmpty()][System.String[]]$psd1Path
, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = 'Path to custom files.')][ValidateNotNullOrEmpty()][System.String[]]$CustomFolderPath
, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = 'Path to examples files.')][ValidateNotNullOrEmpty()][System.String[]]$ExamplesFolderPath
, [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, HelpMessage = 'Path to test files.')][ValidateNotNullOrEmpty()][System.String[]]$TestFolderPath
)
Try {
If (!(Test-Path -Path:($CustomFolderPath))) {
New-Item -Path:($CustomFolderPath) -ItemType:('Directory')
}
$IndentChar = ' '
# Get AutoRest Versions
$coreRegex = [regex]'autorest_core@([0-9]+\.[0-9]+\.[0-9]+)'
$PSRegex = [regex]'autorest_powershell@([0-9]+\.[0-9]+\.[0-9]+)'
$autorestRaw = npx autorest --version
$autorestCore = (Select-String -InputObject $autorestRaw -Pattern $coreRegex).Matches.Groups[1].value
$autorestPS = (Select-String -InputObject $autorestRaw -Pattern $PSRegex).Matches.Groups[1].value
$MSCopyrightHeader = "`n# ----------------------------------------------------------------------------------`n# Code generated by Microsoft (R) AutoRest Code Generator (autorest: $autorestCore, generator: @autorest/powershell@$autorestPS)`n# Changes may cause incorrect behavior and will be lost if the code is regenerated.`n# ----------------------------------------------------------------------------------`n"
$Divider = '|#|#|#|#|#|#|#|#|#|#|#|#|#|#|#|'
$FunctionTemplate = "{0}`nFunction {1}`n{{`n$($IndentChar){2}`n$($IndentChar)Param(`n{3}`n$($IndentChar))`n$($IndentChar)Begin`n$($IndentChar){{`n{4}`n$($IndentChar)}}`n$($IndentChar)Process`n$($IndentChar){{`n{5}`n$($IndentChar)}}`n$($IndentChar)End`n$($IndentChar){{`n{6}`n$($IndentChar)}}`n}}"
# Get config values
$Config = Get-Content -Path:($ConfigPath) | ConvertFrom-Yaml
$ConfigPrefix = $Config.prefix | Select-Object -First 1
$ConfigCustomFunctionPrefix = $Config.customFunctionPrefix
# Pagination Mapping
$CustomPaginationMap = @{
'Get-JCSDKGsuiteUsersToImport' = @{
skip = 'pageToken'
limit = 'maxResults'
nextToken = '$result.nextPageToken'
}
'Get-JcSdkGsuiteUsersToImportFormatted' = @{
skip = 'pageToken'
limit = 'maxResults'
nextToken = '$result.nextPageToken'
}
'Get-JCSDKOffice365UsersToImport' = @{
skip = 'skipToken'
limit = 'top'
nextToken = '$result.skipToken'
}
}
# Misc Functions
Function Convert-GeneratedToCustom ([System.String]$InputString, [System.String]$ConfigPrefix, [System.String]$ConfigCustomFunctionPrefix) {
# Swap out SDK prefix for customFunction prefix
$InputString = $InputString.Replace($ConfigPrefix, $ConfigCustomFunctionPrefix)
# Remove weird output conversion for the customFunctions
$OutputMatches = $InputString | Select-String -Pattern:([regex]'(?<=\()(.*?)(?=\)\.ToJsonString\(\) \| ConvertFrom-Json)') -AllMatches
$OutputMatches.Matches | ForEach-Object {
$OutputMatchesFind = '({0}).ToJsonString() | ConvertFrom-Json' -f ($_.Value)
$InputString = $InputString.Replace($OutputMatchesFind, $_.Value)
}
Return $InputString
}
# Load the module
$ImportedModule = Import-Module $psd1Path -Force -PassThru
# Start generation
If (Get-Module -Name($ImportedModule.Name)) {
# Get list of commands from module
$Commands = Get-Command -Module:($ImportedModule.Name) # -Verb:('Get') -Noun:('JcSdkInternalEvent') # Use to troubleshoot single command
ForEach ($Command In $Commands) {
# Get module name
$ModuleName = If ($Command.Module.Name -like '*.internal') {
$Command.Module.Name.Replace('.internal', '')
} Else {
$Command.Module.Name
}
# Create new function name
$CommandName = $Command.Name
$NewCommandName = $CommandName.Replace($ConfigPrefix, $ConfigCustomFunctionPrefix)
# Get content from sdk function
$CommandFilePath = $Command.ScriptBlock.File
Write-Host ("[STATUS] Command Source: $CommandFilePath") -BackgroundColor:('Black') -ForegroundColor:('Magenta')
$CommandFilePathContent = Get-Content -Path:($CommandFilePath) -Raw
$MSCopyrightHeader = "`n<#`n.Synopsis`n"
$Divider = "`n[SPLIT]`n<#`n.Synopsis`n"
$FunctionContent = If ($CommandFilePath -like '*ProxyCmdletDefinitions.ps1') {
<# When the autorest generated module has been installed and imported from the PSGallery all the
cmdlets will exist in a single ProxyCmdletDefinitions.ps1 file. We need to parse
out the specific function in order to gather the parts we need to copy over. #>
# Write-Host "hitting condition"
$ProxyContent = $CommandFilePathContent.Replace($MSCopyrightHeader, $Divider)
$ProxyContentSplit = $ProxyContent.Split("[SPLIT]")
foreach ($functionSplit in $ProxyContentSplit) {
if ($functionSplit -match "function $CommandName {") {
# return the matched content
$functionSplit
}
}
} Else {
<# When the autorest generated module has been imported from a local psd1 module the function will
remain in their individual files. #>
$CommandFilePathContent
}
# Extract the sections we want to copy over to our new function.
$Params = $FunctionContent | Select-String -Pattern:([regex]'(?s)( \[Parameter)(.*?)(\})') -AllMatches
$OutputType = (($FunctionContent | Select-String -Pattern:([regex]'(\[OutputType)(.*?)(\]\s+)')).Matches.Value).TrimEnd()
$CmdletBinding = (($FunctionContent | Select-String -Pattern:([regex]'(\[CmdletBinding)(.*?)(\]\s+)')).Matches.Value).TrimEnd()
$DefaultParameterSetName = ($CmdletBinding | Select-String -Pattern:([regex]"(?<=DefaultParameterSetName=')(.*?)(?=')")).Matches.Value
# Strip out parameters that match "DontShow"
if ($NewCommandName -in $CustomPaginationMap.Keys){
$ParameterContent = ($Params.Matches.Value | Where-Object { $_ -notlike "*`${$($CustomPaginationMap.$NewCommandName.limit)}*" -and $_ -notlike "*`${$($CustomPaginationMap.$NewCommandName.skip)}*" })
$ContainsLimit = $Params.Matches.Value | Where-Object { $_ -like "*`${$($CustomPaginationMap.$NewCommandName.limit)}*" }
$ContainsSkip = $Params.Matches.Value | Where-Object { $_ -like "*`${$($CustomPaginationMap.$NewCommandName.skip)}*" }
$skip = $($CustomPaginationMap.$NewCommandName.skip)
$limit = $($CustomPaginationMap.$NewCommandName.limit)
$tokenizedPaginate = $true
$skipToken = $($CustomPaginationMap.$NewCommandName.nextToken)
} else {
if ($NewCommandName -eq 'Get-JcSdkEvent') {
$ParameterContent = ($Params.Matches.Value)
} else {
$ParameterContent = ($Params.Matches.Value | Where-Object { $_ -notlike '*${Limit}*' -and $_ -notlike '*${Skip}*' })
}
$ContainsLimit = $Params.Matches.Value | Where-Object { $_ -like '*Limit*' }
$ContainsSkip = $Params.Matches.Value | Where-Object { $_ -like '*Skip*' }
$skip = 'Skip'
$limit = 'Limit'
$tokenizedPaginate = $false
$skipToken = '$ResultCount'
}
$ParameterSetLimit = ($ContainsLimit | Select-String -Pattern:([regex]"(?<=ParameterSetName=')(.*?)(?=')")).Matches.Value
$ParameterSetSkip = ($ContainsSkip | Select-String -Pattern:([regex]"(?<=ParameterSetName=')(.*?)(?=')")).Matches.Value
# Build CmdletBinding
If (-not [System.String]::IsNullOrEmpty($OutputType)) {
$CmdletBinding = "$($OutputType)`n$($IndentChar)$($CmdletBinding)"
}
# Build $BeginContent, $ProcessContent, and $EndContent
$BeginContent = @()
$ProcessContent = @()
$EndContent = @()
# Results logic - If the output model is undefined in the swagger spec
$ResultsLogic = If ($Command.OutputType -like "$ModuleName.Models.*ApplicationJson*") {
@"
($($ImportedModule.Name)\$($CommandName) -ErrorAction SilentlyContinue -errorVariable sdkError @PSBoundParameters); if (-not [System.String]::IsNullOrEmpty(`$Result)) { `$Result = `$Result.ToJsonString() | ConvertFrom-Json };
"@
} Else {
"$($ImportedModule.Name)\$($CommandName) @PSBoundParameters -errorAction SilentlyContinue -errorVariable sdkError"
}
If ($Command.Verb -in ('Get', 'Search')) {
# Add paginate parameter if function contains Limit or Skip parameters
If (-not [System.String]::IsNullOrEmpty($ContainsSkip) -or -not [System.String]::IsNullOrEmpty($ContainsLimit)) {
$ParameterSetLimitSkip = If (-not [System.String]::IsNullOrEmpty($ParameterSetLimit) -or -not [System.String]::IsNullOrEmpty($ParameterSetSkip)) {
$ParameterSetLimitSkipArray = @()
If (-not [System.String]::IsNullOrEmpty($ParameterSetLimit)) {
$ParameterSetLimit | ForEach-Object {
$ParameterSetLimitSkipArray += $_.Trim()
}
}
If (-not [System.String]::IsNullOrEmpty($ParameterSetSkip)) {
$ParameterSetSkip | ForEach-Object {
$ParameterSetLimitSkipArray += $_.Trim()
}
}
"'$(($ParameterSetLimitSkipArray | Select-Object -Unique ) -join "','")'"
} Else {
"'$(($DefaultParameterSetName | Select-Object -Unique) -join "','")'"
}
If (-not [System.String]::IsNullOrEmpty($ParameterContent)) {
If ($ParameterContent.Count -eq 1) {
# Add paginate parameter
$ParameterContent += ",$($IndentChar)[Parameter(DontShow)]`n$($IndentChar)[System.Boolean]`n$($IndentChar)# Set to `$true to return all results. This will overwrite any skip and limit parameter.`n$($IndentChar)`$Paginate = `$true"
} Else {
$ParameterContent += "$($IndentChar)[Parameter(DontShow)]`n$($IndentChar)[System.Boolean]`n$($IndentChar)# Set to `$true to return all results. This will overwrite any skip and limit parameter.`n$($IndentChar)`$Paginate = `$true"
}
}
}
# Build script content
If ($ModuleName -eq 'JumpCloud.SDK.DirectoryInsights') {
# Build "Begin" block
$BeginContent += @"
`$Results = @()
`$PSBoundParameters.Add('HttpPipelineAppend', {
param(`$req, `$callback, `$next)
# call the next step in the Pipeline
`$ResponseTask = `$next.SendAsync(`$req, `$callback)
`$global:JCHttpRequest = `$req
`$global:JCHttpRequestContent = If (-not [System.String]::IsNullOrEmpty(`$req.Content)) { `$req.Content.ReadAsStringAsync() }
`$global:JCHttpResponse = `$ResponseTask
# `$global:JCHttpResponseContent = If (-not [System.String]::IsNullOrEmpty(`$ResponseTask.Result.Content)) { `$ResponseTask.Result.Content.ReadAsStringAsync() }
Return `$ResponseTask
}
)
"@
# Build "Process" block
# Add paginate logic if function contains Limit and Skip parameters
If (-not [System.String]::IsNullOrEmpty($ContainsSkip) -or -not [System.String]::IsNullOrEmpty($ContainsLimit)) {
$ProcessContent += @"
If (`$Paginate -and `$PSCmdlet.ParameterSetName -in ($ParameterSetLimitSkip)) {
`$PSBoundParameters.Remove('Paginate') | Out-Null
Do {
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw `$sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
If (`$limit) {
`$Results += `$Result
Break
} elseif (`$JCHttpResponse.Result.Headers.Contains('X-Search_after')) {
If (-not [System.String]::IsNullOrEmpty(`$Result)) {
`$XResultSearchAfter = (`$JCHttpResponse.Result.Headers.GetValues('X-Search_after') | ConvertFrom-Json);
If ([System.String]::IsNullOrEmpty(`$PSBoundParameters.SearchAfter)) {
If ([System.String]::IsNullOrEmpty(`$PSBoundParameters.Body)) {
`$PSBoundParameters.Add('SearchAfter', `$XResultSearchAfter)
} Else {
`$PSBoundParameters.Body.SearchAfter = `$XResultSearchAfter
}
} Else {
`$PSBoundParameters.SearchAfter = `$XResultSearchAfter
}
`$XResultCount = `$JCHttpResponse.Result.Headers.GetValues('X-Result-Count')
`$XLimit = `$JCHttpResponse.Result.Headers.GetValues('X-Limit')
`$Results += `$Result
Write-Debug ("ResultCount: `$(`$XResultCount); Limit: `$(`$XLimit); XResultSearchAfter: `$(`$XResultSearchAfter); ");
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
}
} Else {
`$Results += `$Result
Break
}
}
While (`$XResultCount -eq `$XLimit -and -not [System.String]::IsNullOrEmpty(`$Result))
} Else {
`$PSBoundParameters.Remove('Paginate') | Out-Null
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw `$sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
If (-not [System.String]::IsNullOrEmpty(`$Result)) {
`$Results += `$Result
}
}
"@
} Else {
$ProcessContent += @"
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw `$sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
If (-not [System.String]::IsNullOrEmpty(`$Result))
{
`$Results += `$Result
}
"@
}
# Build "End" block
$EndContent += @"
# Clean up global variables
`$GlobalVars = @('JCHttpRequest', 'JCHttpRequestContent', 'JCHttpResponse', 'JCHttpResponseContent')
`$GlobalVars | ForEach-Object {
If ((Get-Variable -Scope:('Global')).Where( { `$_.Name -eq `$_ })) { Remove-Variable -Name:(`$_) -Scope:('Global') }
}
Return `$Results
"@
} ElseIf ($ModuleName -In ('JumpCloud.SDK.V1', 'JumpCloud.SDK.V2')) {
# Build "Begin" block
$BeginContent += @"
`$Results = @()
`$PSBoundParameters.Add('HttpPipelineAppend', {
param(`$req, `$callback, `$next)
# call the next step in the Pipeline
`$ResponseTask = `$next.SendAsync(`$req, `$callback)
`$global:JCHttpRequest = `$req
`$global:JCHttpRequestContent = If (-not [System.String]::IsNullOrEmpty(`$req.Content)) { `$req.Content.ReadAsStringAsync() }
`$global:JCHttpResponse = `$ResponseTask
# `$global:JCHttpResponseContent = If (-not [System.String]::IsNullOrEmpty(`$ResponseTask.Result.Content)) { `$ResponseTask.Result.Content.ReadAsStringAsync() }
Return `$ResponseTask
}
)
"@
# Build "Process" block
# Add paginate logic if function contains Limit and Skip parameters
If (-not [System.String]::IsNullOrEmpty($ContainsSkip) -or -not [System.String]::IsNullOrEmpty($ContainsLimit)) {
$ProcessContent += @"
If (`$Paginate -and `$PSCmdlet.ParameterSetName -in ($ParameterSetLimitSkip)) {
`$PSBoundParameters.Remove('Paginate') | Out-Null
"@
If (-not [System.String]::IsNullOrEmpty($ContainsLimit)) {
$ProcessContent += @"
If ([System.String]::IsNullOrEmpty(`$PSBoundParameters.$limit)) {
`$PSBoundParameters.Add('$limit', 100)
}
"@
}
If ( (-not [System.String]::IsNullOrEmpty($ContainsSkip)) -and ($tokenizedPaginate -eq $false) ) {
$ProcessContent += @"
If ([System.String]::IsNullOrEmpty(`$PSBoundParameters.$skip)) {
`$PSBoundParameters.Add('$skip', 0)
}
"@
}
$ProcessContent += @"
Do {
"@
If (-not [System.String]::IsNullOrEmpty($ContainsLimit)) {
$ProcessContent += @"
Write-Debug (`"Limit: `$(`$PSBoundParameters.$limit); `");
"@
}
If (-not [System.String]::IsNullOrEmpty($ContainsSkip)) {
$ProcessContent += @"
Write-Debug (`"Skip: `$(`$PSBoundParameters.$skip); `");
"@
}
$ProcessContent += @"
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw `$sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
`$Result = If ('Results' -in `$Result.PSObject.Properties.Name) {
`$Result.results
} Else {
`$Result
}
If (-not [System.String]::IsNullOrEmpty(`$Result))
{
"@
If ((-not [System.String]::IsNullOrEmpty($ContainsLimit) -or -not [System.String]::IsNullOrEmpty($ContainsSkip)) -And ($tokenizedPaginate -eq $false)) {
$ProcessContent += @"
`$ResultCount = (`$Result | Measure-Object).Count;
"@
$ProcessContent += @"
`$Results += `$Result;
"@
}
If ((-not [System.String]::IsNullOrEmpty($ContainsLimit) -or -not [System.String]::IsNullOrEmpty($ContainsSkip)) -And ($tokenizedPaginate -eq $true)) {
$ProcessContent += @"
`$ResultCount = (`$Result.users | Measure-Object).Count;
"@
$ProcessContent += @"
`$Results += `$Result.users;
"@
}
If ((-not [System.String]::IsNullOrEmpty($ContainsSkip)) -And ($tokenizedPaginate -eq $false)) {
$ProcessContent += @"
`$PSBoundParameters.$skip += $skipToken
"@
}
If ((-not [System.String]::IsNullOrEmpty($ContainsSkip)) -And ($tokenizedPaginate -eq $true)) {
$ProcessContent += @"
`$PSBoundParameters.$skip = $skipToken
"@
}
$ProcessContent += @"
}
}
"@
$ProcessContent += If (-not [System.String]::IsNullOrEmpty($ContainsLimit)) {
@"
While (`$ResultCount -eq `$PSBoundParameters.$limit -and -not [System.String]::IsNullOrEmpty(`$Result))
"@
} Else {
@"
While (-not [System.String]::IsNullOrEmpty(`$Result))
"@
}
if ($tokenizedPaginate -eq $false){
$ProcessContent += @"
} Else {
`$PSBoundParameters.Remove('Paginate') | Out-Null
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw $`sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw $`sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
`$Result = If ('Results' -in `$Result.PSObject.Properties.Name) {
`$Result.results
} Else {
`$Result
}
If (-not [System.String]::IsNullOrEmpty(`$Result)) {
`$Results += `$Result;
}
}
"@
} elseif ($tokenizedPaginate -eq $true){
$ProcessContent += @"
} Else {
`$PSBoundParameters.Remove('Paginate') | Out-Null
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw `$sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
`$Result = If ('Results' -in `$Result.PSObject.Properties.Name) {
`$Result.results
} Else {
`$Result
}
If (-not [System.String]::IsNullOrEmpty(`$Result)) {
`$Results += `$Result.users;
}
}
"@
}
} Else {
$ProcessContent += @"
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Result = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw $sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
`$Result = If ('Results' -in `$Result.PSObject.Properties.Name) {
`$Result.results
} Else {
`$Result
}
If (-not [System.String]::IsNullOrEmpty(`$Result)) {
`$Results += `$Result;
}
"@
}
# Build "End" block
$EndContent += @"
# Clean up global variables
`$GlobalVars = @('JCHttpRequest', 'JCHttpRequestContent', 'JCHttpResponse','JCHttpResponseContent')
`$GlobalVars | ForEach-Object {
If ((Get-Variable -Scope:('Global')).Where( { `$_.Name -eq `$_ })) { Remove-Variable -Name:(`$_) -Scope:('Global') }
}
Return `$Results
"@
} Else {
Write-Error ('Unknown module $($ModuleName)')
}
} ElseIf ($Command.Verb -in ('Restart', 'Invoke', 'New', 'Set', 'Remove', 'Start', 'Unlock', 'Update', 'Reset', 'Grant', 'Import', 'Clear', 'Lock', 'Stop', 'Sync', 'Initialize')) {
# Build "Begin" block
$BeginContent += @"
`$Results = @()
`$PSBoundParameters.Add('HttpPipelineAppend', {
param(`$req, `$callback, `$next)
# call the next step in the Pipeline
`$ResponseTask = `$next.SendAsync(`$req, `$callback)
`$global:JCHttpRequest = `$req
# `$global:JCHttpRequestContent = If (-not [System.String]::IsNullOrEmpty(`$req.Content)) { `$req.Content.ReadAsStringAsync() }
`$global:JCHttpResponse = `$ResponseTask
# `$global:JCHttpResponseContent = If (-not [System.String]::IsNullOrEmpty(`$ResponseTask.Result.Content)) { `$ResponseTask.Result.Content.ReadAsStringAsync() }
Return `$ResponseTask
}
)
"@
# Build "Process" block
# temp fix for Set-JcSdkUserAssociation TODO: remove when DE-2630 is done
if ($NewCommandName -eq ("Set-JcSdkUserAssociation" -or "Set-JcSdkSystemAssociation")) {
$ProcessContent += @"
if ((-not `$PSBoundParameters['attributes']) -and (`$PSBoundParameters['op'] -eq 'remove')) {
`$PSBoundParameters.Add('attributes', @{ '' = '' })
} elseif ((`$PSBoundParameters['body']) -And (`$Body.Op -eq 'remove')) {
`$Body.Attributes = @{ '' = '' }
}
"@
}
$ProcessContent += @"
`$maxRetries = 4
`$resultCounter = 0
:retryLoop do {
`$resultCounter++
`$Results = $ResultsLogic
If (`$sdkError){
If (`$resultCounter -eq `$maxRetries){
throw `$sdkError
}
If (`$JCHttpResponse.Result.StatusCode -eq "503") {
Write-Warning ("503: Service Unavailable - retrying in " + (`$resultCounter * 5) + " seconds.")
} else {
throw `$sdkError
}
} else {
break retryLoop
}
Start-Sleep -Seconds (`$resultCounter * 5)
} while (`$resultCounter -lt `$maxRetries)
"@
# Build "End" block
$EndContent += @"
Write-Debug ('HttpRequest: ' + `$JCHttpRequest);
# Write-Debug ('HttpRequestContent: ' + `$JCHttpRequestContent.Result);
Write-Debug ('HttpResponse: ' + `$JCHttpResponse.Result);
# Write-Debug ('HttpResponseContent: ' + `$JCHttpResponseContent.Result);
# Clean up global variables
`$GlobalVars = @('JCHttpRequest', 'JCHttpRequestContent', 'JCHttpResponse', 'JCHttpResponseContent')
`$GlobalVars | ForEach-Object {
If ((Get-Variable -Scope:('Global')).Where( { `$_.Name -eq `$_ })) {
Remove-Variable -Name:(`$_) -Scope:('Global')
}
}
Return `$Results
"@
} Else {
Write-Error ("Unmapped command: $CommandName")
$null
}
If (-not [System.String]::IsNullOrEmpty($BeginContent) -and -not [System.String]::IsNullOrEmpty($ProcessContent) -and -not [System.String]::IsNullOrEmpty($EndContent)) {
# Build "Function"
$NewScript = $FunctionTemplate -f '', $NewCommandName, $CmdletBinding, ($ParameterContent -join ", `n`n"), ($BeginContent -join "`n"), ($ProcessContent -join "`n"), ($EndContent -join "`n")
# Fix line endings
$NewScript = $NewScript.Replace("`r`n", "`n").Trim()
# Export the function
Write-Host ("[STATUS] Building: $NewCommandName") -BackgroundColor:('Black') -ForegroundColor:('Magenta') # | Tee-Object -FilePath:($LogFilePath) -Append
$OutputFilePath = "$CustomFolderPath/$NewCommandName.ps1"
[System.IO.File]::WriteAllLines($OutputFilePath, $NewScript, (New-Object System.Text.UTF8Encoding $true))
}
}
} Else {
Write-Error ('No modules found.')
}
} Catch {
Get-Error
Write-Error ($_)
}