-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSTSwagger.ps1
More file actions
846 lines (752 loc) · 28.7 KB
/
STSwagger.ps1
File metadata and controls
846 lines (752 loc) · 28.7 KB
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
Param (
[Parameter(Mandatory=$True, ParameterSetName="Download")]
[Parameter(Mandatory=$True, ParameterSetName="Local")]
[ValidateNotNullOrEmpty()]
[ValidatePattern("(((f|ht){1}(tp|tps):\/\/)[\w\d\S]+)")]
[string] $BaseURI,
[Parameter(Mandatory=$True, ParameterSetName="Download")]
[ValidateNotNullOrEmpty()]
[ValidatePattern("(((f|ht){1}(tp|tps):\/\/)[\w\d\S]+)")]
[string] $SwaggerJsonURI,
[Parameter(Mandatory=$True, ParameterSetName="Local")]
[ValidateNotNullOrEmpty()]
[string] $SwaggerJsonFile,
[Parameter(Mandatory=$False, ParameterSetName="Download")]
[Parameter(Mandatory=$False, ParameterSetName="Local")]
[ValidateLength(0,5)]
[ValidatePattern("^([A-Za-z0-9]){0,5}$")]
[string] $CmdletIdentifier,
[Parameter(Mandatory=$True, ParameterSetName="Download")]
[Parameter(Mandatory=$True, ParameterSetName="Local")]
[ValidateNotNullOrEmpty()]
[string] $OutputDirectory,
[Parameter(Mandatory=$True, ParameterSetName="Download")]
[Parameter(Mandatory=$True, ParameterSetName="Local")]
[ValidatePattern("^([A-Za-z0-9]){1,50}$")]
[string] $ModuleName,
[Parameter(Mandatory=$False, ParameterSetName="Download")]
[Parameter(Mandatory=$False, ParameterSetName="Local")]
[ValidateNotNullOrEmpty()]
[string[]] $AdditionalScripts,
[Parameter(Mandatory=$False, ParameterSetName="Download")]
[Parameter(Mandatory=$False, ParameterSetName="Local")]
[ValidateNotNullOrEmpty()]
[hashtable] $ManifestParameters
)
#Base URI should not contain a forwardslash at the end of the string
$trailingSlashes = "(\\*$)|(\/*$)"
$BaseURI = $BaseURI -ireplace $trailingSlashes, ""
$OutputDirectory = $OutputDirectory -ireplace $trailingSlashes, ""
if ($PSCmdlet.ParameterSetName -eq 'Download') {
$SwaggerJsonURI = $SwaggerJsonURI -ireplace $trailingSlashes, ""
}
#This function converts a raw Swagger Json file to a usable Specification Object
function ConvertTo-STSwaggerSpecification () {
Param (
$SwaggerContent
)
#Build the specification object
$paths = $SwaggerContent.paths | Get-Member -MemberType NoteProperty
[array]$apis = @()
#Iterate through each path and build custom objects that are easier to work with
foreach ($path in $paths) {
$pathObject = $SwaggerContent.paths.($path.name)
$methods = $pathObject | Get-Member -MemberType NoteProperty
#Iterate through each method type eg. Get, Post, Delete, etc.. under each path
#TODO: Add Progress Tracker
foreach ($methodType in $methods) {
$method = $pathObject.($methodType.name)
$methodMembers = $method | Get-Member -MemberType NoteProperty
#Store each property in a hashtable
$apiHT = @{}
foreach ($methodMember in $methodMembers) {
$apiHT.Add((Get-Culture).TextInfo.ToTitleCase($methodMember.Name.ToLower()), $method.($methodMember.Name))
}
$apiHT.Add("Path",$path.Name)
$apiHT.Add("Method",$methodType.Name)
#Turn the hashtable into a custom object
$apis += New-Object -TypeName PSObject -Property $apiHT
}
}
#return the array of custom objects
return $apis
}
#This function downloads / converts a Swagger json file to a PowerShell object
function Get-STSwaggerContent () {
Param (
[Parameter(ParameterSetName="1")]
[Parameter(ParameterSetName="2")]
[string] $Uri,
[Parameter(ParameterSetName="1")]
[Parameter(ParameterSetName="2")]
[string] $OutFile = $null,
[Parameter(ParameterSetName="1")]
[PSCredential] $Credential,
[Parameter(ParameterSetName="2")]
[switch] $UseDefaultCredentials,
[Parameter(ParameterSetName="3")]
[string] $JsonFile
)
if ($PSCmdlet.ParameterSetName -eq "3") {
$content = Get-Content $JsonFile | ConvertFrom-Json
} else {
Invoke-WebRequest -Uri $Uri -OutFile $OutFile -UseDefaultCredentials:$UseDefaultCredentials -Credential $Credential
$content = Get-Content $OutFile | ConvertFrom-Json
if (!$content) { throw "Unable to download Swagger Specification file from: $Uri" }
}
if (!$content) { throw "Unable to load Swagger Specification file." }
return $content
}
#This function converts RestMethods to approved PowerShell verbs
function ConvertFrom-RestMethod () {
Param (
$Method
)
$Methods =@{
Access="Get"
Acquire="Get"
Activate="Initialize"
Add="Add"
Allocate="New"
Analyze="Test"
Append="Add"
Apply="Add"
Approve="Approve"
Assert="Assert"
Assign="Set"
Associate="Join"
Attach="Add"
Authorize="Grant"
Backup="Backup"
Block="Block"
Build="Build"
Bypass="Skip"
Cancel="Stop"
Capture="Export"
Cat="Get"
Change="Rename"
Check="Test"
Checkpoint="Checkpoint"
Clear="Clear"
Clone="Copy"
Close="Close"
Combine="Join"
Compare="Compare"
Compile="Build"
Complete="Complete"
Compress="Compress"
Concatenate="Add"
Configure="Set"
Confirm="Confirm"
Connect="Connect"
Convert="Convert"
ConvertFrom="ConvertFrom"
ConvertTo="ConvertTo"
Copy="Copy"
Create="New"
Cut="Remove"
Debug="Debug"
Delete="Remove"
Deny="Deny"
Deploy="Deploy"
Dir="Get"
Disable="Disable"
Discard="Remove"
Disconnect="Disconnect"
Discover="Find"
Dismount="Dismount"
Display="Show"
Dispose="Remove"
Dump="Get"
Duplicate="Copy"
Edit="Edit"
Enable="Enable"
End="Stop"
Enter="Enter"
Erase="Clear"
Evaluate="Test"
Examine="Get"
Execute="Invoke"
Exit="Exit"
Expand="Expand"
Export="Export"
Failover="Set"
Find="Find"
Finish="Complete"
Flush="Clear"
ForceReboot="Restart"
Format="Format"
Generalize="Reset"
Generate="New"
Get="Get"
Grant="Grant"
Group="Group"
Hide="Hide"
Import="Import"
Initialize="Initialize"
Insert="Add"
Install="Install"
Into="Enter"
Invoke="Invoke"
Is="Test"
Join="Join"
Jump="Skip"
Limit="Limit"
List="Get"
Load="Import"
Locate="Find"
Lock="Lock"
Make="New"
Measure="Measure"
Merge="Merge"
Migrate="Move"
Mount="Mount"
Move="Move"
Name="Move"
New="New"
Notify="Send"
Nullify="Clear"
Obtain="Get"
Open="Open"
Optimize="Optimize"
Out="Out"
Patch="Update"
Pause="Suspend"
Perform="Invoke"
Ping="Ping"
Pop="Pop"
Post="Invoke"
Power="Start"
PowerOff="Stop"
PowerOn="Start"
Produce="Show"
Protect="Protect"
Provision="New"
Publish="Publish"
Purge="Clear"
Push="Push"
Put="Set"
Read="Read"
Reassociate="Move"
Reboot="Restart"
Receive="Receive"
Recover="Restore"
Redo="Redo"
Refresh="Update"
Regenerate="New"
Register="Register"
Reimage="Update"
Release="Publish"
Remove="Remove"
Rename="Rename"
Repair="Repair"
Replace="Update"
Replicate="Copy"
Reprocess="Update"
Request="Request"
Reset="Reset"
Resize="Resize"
Resolve="Resolve"
Restart="Restart"
Restore="Restore"
Restrict="Lock"
Resubmit="Submit"
Resume="Resume"
Retarget="Update"
Retrieve="Get"
Revoke="Revoke"
Run="Start"
Save="Save"
Search="Search"
Secure="Lock"
Select="Select"
Send="Send"
Separate="Split"
Set="Set"
Show="Show"
Shutdown="Stop"
Skip="Skip"
Split="Split"
Start="Start"
Step="Step"
Stop="Stop"
Submit="Submit"
Suggest="Get"
Suspend="Suspend"
Swap="Switch"
Switch="Switch"
Sync="Sync"
Synch="Sync"
Synchronize="Sync"
Test="Test"
Trace="Trace"
Transfer="Move"
Trigger="Start"
Type="Get"
Unblock="Unblock"
Undelete="Restore"
Undo="Undo"
Uninstall="Uninstall"
Unite="Join"
Unlock="Unlock"
Unmark="Clear"
Unprotect="Unprotect"
Unpublish="Unpublish"
Unregister="Unregister"
Unrestrict="Unlock"
Unsecure="Unlock"
Unset="Clear"
Update="Update"
Upgrade="Update"
Use="Use"
Validate="Test"
Verify="Test"
Wait="Wait"
Watch="Watch"
Wipe="Clear"
Write="Write"
}
$convertedMethod = $Methods.$Method
if (!$convertedMethod) { Write-Error "Unable to convert $Method." }
return $convertedMethod
}
#This function creates Approved PowerShell function names
function Get-STSwaggerFunctionName () {
Param (
[string] $Method,
[string] $OperationId,
[string] $Tag,
[string] $CmdletIdentifier
)
$verb = ConvertFrom-RestMethod -Method $Method
#Doctor the Operation Id. Replace any of the matches found here.
$noun = $OperationId -ireplace $Method, ""
$noun = $noun -ireplace "api_", ""
$noun = $noun -ireplace "(A|a)(P|p)(I|i)$", ""
$noun = $noun -ireplace "_$", ""
#TODO: Might be worth trying to deduplicate consecutive words.
#Build the approved function name here.
return ("{0}-{1}{2}" -f $verb, $CmdletIdentifier, $noun)
}
#This function builds a grouped object containing function names and parameter sets
# that is used to create the PowerShell API module
function Initialize-STSwaggerAPI () {
Param (
$STSwaggerSpecification,
[string]$ModuleName,
[string]$CmdletIdentifier
)
#Check for multiple tags
if ($STSwaggerSpecification | Where-Object {$_.Tags.Count -eq 2}) {
Write-Warning "Possible errors could occur."
}
#Get each tag. There will be one cmdlet for each tag
$tags = $STSwaggerSpecification | Select-Object -Property Tags,Method,OperationId,Path -Unique
#Clear the array within the tags.
$tags | ForEach-Object {$_.Tags = $_.Tags -join ","}
#Group the tags together by tag. Each Tag will be its own Module file
$tags = $tags | Group-Object -Property Tags
$functionSchema = @{Function="";OperationIds="";Method="";Tags=""; Module=""; Path = ""}
$functionObjects = @()
#Loop through each module
foreach ($module in $tags) {
#Loop through each function in each module and generate the raw API object that is used to create the function
foreach ($function in $module.Group) {
$functionObject = New-Object -TypeName PSObject -Property $functionSchema
$functionObject.Function = Get-STSwaggerFunctionName -Method $function.Method -OperationId $function.OperationId -Tag $function.Tags -CmdletIdentifier $CmdletIdentifier
$functionObject.OperationIds = $function.Operationid
$functionObject.Method = $function.Method
$functionObject.Tags = $function.Tags
$functionObject.Module = $module.Name
$functionObject.Path = $function.Path
$functionObjects += $functionObject
}
}
#TODO: Add a check to ensure duplicate function names are not created.
return $functionObjects
}
#This converts the Rest parameter type to a PowerShell type
function ConvertTo-PowerShellType () {
Param (
$ParameterObject
)
if ($ParameterObject.In -eq "body") {
return "object"
}
if ($ParameterObject.Schema -ne $null) {
#Pull from the schema
if ($ParameterObject.Schema.Type -eq "array") {
if ($ParameterObject.Schema.items.type -ne $null) {
return "{0}[]" -f $ParameterObject.Schema.items.type
} else {
return "object[]"
}
} else {
#It's probably a definition reference
}
}
if ($ParameterObject.Type -eq "string") {
return "string"
} elseif ($ParameterObject.Type -eq "integer") {
return "int"
} elseif ($ParameterObject.Type -eq "boolean") {
return "switch"
} else {
return "object"
}
}
#This generates the Param() block for a function using the specification and the API object
function Get-STSwaggerPowerShellParams {
Param (
$STSwaggerAPIObject,
$STSwaggerSpecification
)
#Get all the proper specifications for the API object
$specs = $STSwaggerSpecification | Where-Object {$STSwaggerAPIObject.OperationIds.Contains($_.OperationId)}
#Loop through each specification and build the parameter sets
$parameterSets = @()
# Loop through each specification
foreach ($spec in $specs) {
#Loop through each parameter in each specification
foreach ($parameter in $spec.Parameters) {
#Add specific properties
$tempParam = New-Object -TypeName PSObject -Property @{Name = $parameter.name; Type = $parameter.type; Mandatory = $parameter.required; HelpMessage = $parameter.description; Schema = $parameter.schema; Sets = [System.Collections.ArrayList]@(); In = $parameter.in}
$tempParam.Sets += $spec.Path
$parameterSets += $tempParam
}
}
#Group the parameterSets based on name
$parameterSets = $parameterSets | Group-Object -Property Name
$defaultParameterSet = ""
#Use the first specification which is usually parameterless
$defaultParameterSet = "[CmdletBinding(DefaultParameterSetName=`"{0}`")]`n" -f $specs[0].Path
$parameterStrings = @()
$parameterString = ""
#Build the parameter set strings
foreach ($parameter in $parameterSets) {
#Get each parameter set name
$parameterString = ""
$uniqueParameterSets = $parameter.Group.Sets | Select-Object -Unique
foreach ($setName in $uniqueParameterSets) {
#$helpMessage = $parameter.Group.HelpMessage | Sort-Object -Descending | Select-Object -First 1
$parameterString += "`t`t[Parameter(Mandatory=`${0}, ParameterSetName='{1}')]`n" -f ($parameter.Group.Mandatory | Select-Object -Unique), $setName
}
$parameterString += "`t`t`t[{0}] `${1}" -f (ConvertTo-PowerShellType $parameter.Group), ($parameter.Group.Name | Select-Object -Unique)
$parameterStrings += $parameterString
}
#Add the credential property using each of the parametersets
$parameterString = ""
foreach ($setName in ($parameterSets.Group.Sets | Select-Object -Unique)) {
#Get each parameter set name
$parameterString += "`t`t[Parameter(Mandatory=`$False, ParameterSetName='{0}')]`n" -f $setName
}
$parameterString += "`t`t`t[PSCredential] `$Credential"
$parameterStrings += $parameterString
#Add the header property for each parameterset
$parameterString = ""
foreach ($setName in ($parameterSets.Group.Sets | Select-Object -Unique)) {
#Get each parameter set name
$parameterString += "`t`t[Parameter(Mandatory=`$False, ParameterSetName='{0}')]`n" -f $setName
}
$parameterString += "`t`t`t[hashtable] `$Headers"
$parameterStrings += $parameterString
return $defaultParameterSet + "`tParam (`n" + ($parameterStrings -join ",`n") + "`n`t)"
}
function Get-STSwaggerPowerShellParameterSetUris () {
Param (
$STSwaggerAPIObject,
$STSwaggerSpecification
)
#Get all the proper specifications for the API object
$specs = $STSwaggerSpecification | Where-Object {$STSwaggerAPIObject.OperationIds.Contains($_.OperationId)}
$switch = @"
`$URI = ""
`tswitch (`$PSCmdlet.ParameterSetName)
`t{
{URIS}
`n`t}
"@
$paths = @()
foreach ($spec in $specs) {
$pathString = "`t`t`"{0}`" " -f $spec.Operationid
$pathStringUri = "`$URI = `"{0}`"" -f $spec.Path
$pathString += "{ " + $pathStringUri + " }"
$paths += $pathString
}
return $switch.Replace("{URIS}", $paths -join "`n")
}
function Get-STSwaggerPowerShellHelp () {
Param (
$STSwaggerAPIObject,
$STSwaggerSpecification
)
#Get all the proper specifications for the API object
$spec = $STSwaggerSpecification | Where-Object {$STSwaggerAPIObject.OperationIds.Contains($_.OperationId)}
[string]$specSummary = $spec.Summary | Select-Object -Unique
if ($specSummary -eq "" -or $specSummary -eq $null) {$specSummary = "No description provided."}
$helpTemplate = @"
<#
.DESCRIPTION
`t{SUMMARY}
{PARAMETERS}
#>
"@
$parameters = @()
$uniqueParameters = $spec.Parameters | Select-Object -Unique
foreach ($parameter in $uniqueParameters) {
$parameterString = ""
$parameterString += ".PARAMETER {0}`n" -f $parameter.name
$parameterDescription = $parameter.description
if (!$parameterDescription -or $parameter.description -eq $null) { $parameterDescription = "No description provided." }
$parameterString += "`t{0}" -f $parameterDescription
$parameters += $parameterString
}
Write-Debug ($helpTemplate.Replace("{SUMMARY}", $specSummary).Replace("{PARAMETERS}", $parameters -join "`n"))
return $helpTemplate.Replace("{SUMMARY}", $specSummary).Replace("{PARAMETERS}", $parameters -join "`n")
}
#Generates the template used to create a function
function New-STSwaggerPowerShellFunctionTemplate {
$template = @"
{HELP}
Function {FUNCTIONNAME} {
{PARAMS}
`$Data = Get-STSwaggerRestURIData -Parameters `$PSBoundParameters -Uri `$PSCmdlet.ParameterSetName
Invoke-STSwaggerRestApi -URI `$Data.URI -Body `$Data.Body -Method {METHOD} -Credential `$Credential -Headers `$Headers
}
"@
#Return the template
return $template
}
function New-STSwaggerPowerShellCoreFunctions {
Param (
$BaseURI,
$CmdletIdentifier
)
$coreFunctions = @"
`n
# This fixes an issue caused in PSVersion 5.1 and lower where Convert*-Json adds extra properties to the converted objects.
if (`$PSVersionTable.PSVersion.Major -lt 6) {
Get-TypeData -TypeName System.Array | Remove-TypeData
}
`$ENV:$CmdletIdentifier`BaseURI = '$($BaseURI -creplace "/$", "")'
function Get-STSwaggerRestUriData () {
Param (
`$Parameters,
`$Uri
)
`$options = @()
[object]`$body = `$null
`$skippedParameters = @(
"Credential",
"Headers",
"Verbose",
"Debug"
"ErrorAction",
"WarningAction",
"InformationAction",
"ErrorVariable",
"WarningVariable",
"InformationVariable",
"OutVariable",
"OutBuffer",
"PipelineVariable"
)
foreach (`$boundParameter in `$Parameters.Keys) {
#Capture the body
if (`$Parameters.`$boundParameter.PSObject.TypeNames.Contains('System.Management.Automation.PSCustomObject') -or
`$Parameters.`$boundParameter.PSObject.TypeNames.Contains('System.Collections.Hashtable')) {
`$body = `$Parameters.`$boundParameter
continue
}
#Exclude various default and supplied parameters
if (`$skippedParameters.Contains(`$boundParameter)) { continue }
if (`$Uri.Contains("{`$boundParameter}")) {
`$Uri = `$Uri.Replace("{`$boundParameter}", `$Parameters.`$boundParameter)
} else {
`$options += "{0}={1}" -f `$boundParameter, `$Parameters.`$boundParameter
}
}
if (`$options) { `$Uri += "?" + (`$options -join "&") }
return @{URI = `$ENV:$CmdletIdentifier`BaseURI + `$Uri; Body = `$body}
}
#This function invokes the rest method
Function Invoke-STSwaggerRestApi {
Param(
[Parameter(Mandatory=`$true)]
[string] `$Uri,
[Parameter(Mandatory=`$true)]
[string] `$Method,
[Parameter(Mandatory=`$false)]
[object] `$Body = `$null,
[Parameter(Mandatory=`$false)]
[PSCredential] `$Credential = `$null,
[Parameter(Mandatory=`$false)]
[System.Collections.IDictionary] `$Headers = `$null
)
Write-Host `$Method.ToUpper() `$Uri -ForegroundColor Magenta
`$useDefaultCredentials = `$Credential -eq `$null
`$result = `$null
try {
`$result = Invoke-RestMethod -Uri `$URI -Method `$Method -Body (`$Body | ConvertTo-Json -Depth 50) -ContentType "application/json" -Credential `$Credential -UseDefaultCredentials:`$useDefaultCredentials -Headers `$Headers
} catch [System.Net.WebException] {
Write-Warning `$_.Exception.Message
Write-Host `$_.ErrorDetails.Message -ForegroundColor Yellow
}
if (!`$result -or `$result -eq "null") {
return `$null
}
return `$result
}
# Description: This simple function allows you to typically convert the results from a Get REST method
# to a hashtable that can be passed directly back into a Post command. This is very useful
# when you just need to make an update to an item, but the method requires a body.
# Author: Adam Bertram
# Source: https://4sysops.com/archives/convert-json-to-a-powershell-hash-table/
function ConvertTo-Hashtable {
[CmdletBinding()]
[OutputType('hashtable')]
param (
[Parameter(ValueFromPipeline)]
`$InputObject
)
process {
## Return null if the input is null. This can happen when calling the function
## recursively and a property is null
if (`$null -eq `$InputObject) {
return `$null
}
## Check if the input is an array or collection. If so, we also need to convert
## those types into hash tables as well. This function will convert all child
## objects into hash tables (if applicable)
if (`$InputObject -is [System.Collections.IEnumerable] -and `$InputObject -isnot [string]) {
`$collection = @(
foreach (`$object in `$InputObject) {
ConvertTo-Hashtable -InputObject `$object
}
)
## Return the array but don't enumerate it because the object may be pretty complex
Write-Output -NoEnumerate `$collection
} elseif (`$InputObject -is [psobject]) { ## If the object has properties that need enumeration
## Convert it to its own hash table and return it
`$hash = @{}
foreach (`$property in `$InputObject.PSObject.Properties) {
`$hash[`$property.Name] = ConvertTo-Hashtable -InputObject `$property.Value
}
`$hash
} else {
## If the object isn't an array, collection, or other object, it's already a hash table
## So just return it.
`$InputObject
}
}
}
"@
return $coreFunctions
}
#Converts the STSwaggerAPI object to a PowerShell API
function ConvertTo-STSwaggerPowerShellAPI () {
Param (
$STSwaggerAPI,
$STSwaggerSpecification,
$BaseURI
)
$functions = @()
foreach ($STSwaggerAPIObject in $STSwaggerAPI) {
#Generate the template
$functionBody = New-STSwaggerPowerShellFunctionTemplate
#Generate the parameters
$params = Get-STSwaggerPowerShellParams -STSwaggerAPIObject $STSwaggerAPIObject -STSwaggerSpecification $STSwaggerSpecification
#Generate the URIs
$uris = Get-STSwaggerPowerShellParameterSetUris -STSwaggerAPIObject $STSwaggerAPIObject -STSwaggerSpecification $STSwaggerSpecification
$help = Get-STSwaggerPowerShellHelp -STSwaggerAPIObject $STSwaggerAPIObject -STSwaggerSpecification $STSwaggerSpecification
#Generate the mapping
$functionBody = $functionBody.Replace("{PARAMS}", $params)
#$functionBody = $functionBody.Replace("{URISWITCH}", $uris)
$functionBody = $functionBody.Replace("{FUNCTIONNAME}", $STSwaggerAPIObject.Function)
$functionBody = $functionBody.Replace("{HELP}", $help)
$functionBody = $functionBody.Replace("{METHOD}", $STSwaggerAPIObject.Method)
$function = New-Object -TypeName PSObject -Property @{CmdletName = $STSwaggerAPIObject.Function; Module = $STSwaggerAPIObject.Module; Function = $functionBody}
$functions += $function
}
return $functions
}
$ModuleDirectory = "{0}\{1}" -f $OutputDirectory, $ModuleName
$SwaggerOutFile = "{0}\{1}SwaggerSpecification.json" -f $ModuleDirectory, $CmdletIdentifier
$PowerShellModuleFile = "{0}\{1}.psm1" -f $ModuleDirectory, $ModuleName
$PowerShellManifestFile = "{0}\{1}.psd1" -f $ModuleDirectory, $ModuleName
#Make the module output directory
if (!(Test-Path $ModuleDirectory)) {
New-Item $ModuleDirectory -ItemType Directory | Out-Null
}
#Load the swagger specification file
$swaggerContent = ""
if ($PSCmdlet.ParameterSetName -eq "Download" -or $PSCmdlet.ParameterSetName -eq "__AllParameterSets") {
Write-Host "Downloading Specification File."
$swaggerContent = Get-STSwaggerContent -Uri $SwaggerJsonURI -UseDefaultCredentials -OutFile $SwaggerOutFile
} else {
$swaggerContent = Get-STSwaggerContent -JsonFile $SwaggerJsonFile
}
if (!$swaggerContent) {
Write-Error "Unable to load Swagger Specification content."
exit
}
#Format the swagger specification
Write-Host "Creating the STSwagger specification..."
$specification = ConvertTo-STSwaggerSpecification -SwaggerContent $swaggerContent
if (!$specification) { Write-Error "Unable to create a STSwagger Specification" }
#Build the raw API objects used to create the PowerShell functions
Write-Host "Creating the STSwagger API Objects..."
$rawAPIObjects = Initialize-STSwaggerAPI -STSwaggerSpecification $specification -ModuleName $ModuleName -CmdletIdentifier $CmdletIdentifier
if (!$rawAPIObjects) { Write-Error "Unable to create a STSwagger API objects" }
#Build the PowerShell functions
Write-Host "Building the STSwagger PowerShell API..."
$powershellApi = ConvertTo-STSwaggerPowerShellAPI -STSwaggerAPI $rawAPIObjects -STSwaggerSpecification $specification -BaseURI $BaseURI
if (!$powershellApi) { Write-Error "Unable to build the STSwagger PowerShell API" }
#Build the core functions needed to execute the PowerShell API
Write-Host "Building the STSwagger PowerShell Core API..."
$powershellCoreApi = New-STSwaggerPowerShellCoreFunctions -BaseURI $BaseURI -CmdletIdentifier $CmdletIdentifier
if (!$powershellCoreApi) { Write-Error "Unable to build the STSwagger PowerShell Core API" }
#Create the files
Write-Host "Writing the API out to : $PowerShellModuleFile"
$powershellApi.Function > $PowerShellModuleFile
$powershellCoreApi >> $PowerShellModuleFile
#Make the module manifest
[System.Collections.ArrayList]$functionsToExport = $powershellApi.CmdletName
$functionsToExport.Add('ConvertTo-Hashtable') | Out-Null
if (!$ManifestParameters) {
Write-Host "Using default manifest parameters..."
$ManifestParameters = @{
Path = $PowerShellManifestFile;
FunctionsToExport = $functionsToExport;
ScriptsToProcess = $AdditionalScripts;
Description = "This PowerShell API wrapper was generated with the STSwagger API Library.";
HelpInfoUri = "https://github.com/ArmyGuy255a/STSwagger";
Author = "Phillip A. Dieppa";
CompanyName = "Microsoft";
PowerShellVersion = "5.0";
ModuleVersion = [version]::new($swaggerContent.swagger)
RootModule =("{0}.psm1" -f $ModuleName)
}
} else {
Write-Host "Using user supplied manifest parameters..."
}
try {
Write-Host "Creating Module Manifest file."
New-ModuleManifest @ManifestParameters
} catch {
Write-Error "Unable to create the Module Manifest."
}
if ($AdditionalScripts) {
#Copy dependency scripts to the module directory
Write-Host "Copying dependency scripts..."
$AdditionalScripts | ForEach-Object {Copy-Item $_ $ModuleDirectory}
}
Write-Host "Successfully executed the STSwagger PowerShell API Builder. Thanks for using STSwagger to build your PowerShell API!" -ForegroundColor Green
Start-Sleep -Seconds 5
<#Examples
#Using Swagger V1
& .\STSwagger.ps1 -BaseURI https://swaggerwebsite -SwaggerJsonURI "https://swaggerwebsite/swagger/docs/v1" -CmdletIdentifier $CmdletIdentifier -OutputDirectory $OutputDirectory -ModuleName $ModuleName -AdditionalScripts $AdditionalScripts
#Using Swagger V2
& .\STSwagger.ps1 -BaseURI "https://petstore.swagger.io/v2" -SwaggerJsonURI "https://petstore.swagger.io/v2/swagger.json" -CmdletIdentifier "PetStore" -OutputDirectory $OutputDirectory -ModuleName "Petstore" -AdditionalScripts $AdditionalScripts
#>