-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOptimized.Aza.psm1
1524 lines (1446 loc) · 67 KB
/
Optimized.Aza.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
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
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region main
function Connect-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Connect-Aza will retreive a RefreshToken from Microsoft Graph.
.DESCRIPTION
By selecting one of these parameters you log on with the following:
ClientSecret: Will log you on with a ClientSecret.
Certificate: Will log you on with a Certificate.
Thumbprint: Will search for a Certificate under thumbprint on local device and log you on with a Certificate.
UserCredentials: Will log you on with basic authentication.
RedirectUri: Will log you on with MFA Authentication.
The OauthToken is automatically renewed when you use cmdlets.
.PARAMETER Thumbprint
Use a certificate thumbprint to log on with. Connec-Aza will search for the certificate in the cert store.
.PARAMETER Certificate
Use a Cert to log on. you can use where X's is the certificate thumbprint:
$Cert = get-ChildItem 'Cert:\LocalMachine\My\XXXXXXXXXXXXXXXXXXX'
Connect-Aza -Certificate $Cert -ApplicationID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' -Tenant 'XXXXXXXX.onmicrosoft.com'
.PARAMETER ClientSecret
Parameter description
.PARAMETER RedirectUri
Use the RedirectUri in your AzureAD app to connect with MFA.
RedirectUri should look something like this:
'msalXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX://auth'
If you want to know more about how to log in via MFA with a RedirectUri, go to my blog:
https://bwit.blog/how-to-start-with-microsoft-graph-in-powershell/#I_will_use_credentials
.PARAMETER UserCredentials
Use Get-Credential to log on with Basic Authentication.
.PARAMETER ApplicationID
ApplicationID is the ID for the AzureAD application. It should look like this:
'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'
.PARAMETER ManagedIdentity
This is a switch for when it's a Managed Identity authenticating to Azure REST API.
.PARAMETER Tenant
Tenant is the TenantID or onmicrosoft.com address. Don't confuse this with ApplicationID.
I should look like this:
'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'
Or
XXXXXXX.onmicrosoft.com
.PARAMETER Resource
Default Resource is the Azure REST API.
-Resource accepts other Azure REST APIs like the Azure Storage API: https://docs.microsoft.com/en-us/rest/api/storageservices/.
Resource URL is:'https://storage.azure.com/.default'.
.PARAMETER LoginScope
You can only use LoginScope with RedirectUri, but unfortunately the token will always include all permissions the app has.
.PARAMETER Force
Use -Force when you want to overwrite another connection (or Accept the confirmation).
.EXAMPLE
Connect-Aza -ClientSecret '1yD3h~.KgROPO.K1sbRF~XXXXXXXXXXXXX' -ApplicationID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' -Tenant 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'
.EXAMPLE
$Cert = get-ChildItem 'Cert:\LocalMachine\My\XXXXXXXXXXXXXXXXXXX'
Connect-Aza -Certificate $Cert -ApplicationID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' -Tenant 'XXXXXXXX.onmicrosoft.com'
.EXAMPLE
Connect-Aza -UserCredentials $Cred -Tenant 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' -ApplicationID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'
.EXAMPLE
Connect-Aza -redirectUri 'msalXXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX://auth' -Tenant 'XXXXXXXX.onmicrosoft.com' -ApplicationID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX'
.EXAMPLE
Connect-Aza -ClientSecret '1yD3h~.KgROPO.K1sbRF~XXXXXXXXXXXXX' -ApplicationID 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' -Tenant 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX' -Resource 'https://storage.azure.com/.default'
.EXAMPLE
Connect-Aza -ManagedIdentity -Resource 'https://management.azure.com'
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[ValidateScript( { ($_.length -eq 40) -or ([System.Security.Cryptography.X509Certificates.X509Certificate2]$_) })]
[Alias('Thumbprint')]
$Certificate,
[Parameter(Mandatory = $true, ParameterSetName = 'PAT')]
$PAT,
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
[string]
$ClientSecret,
[Parameter(Mandatory = $true, ParameterSetName = 'RedirectUri')]
[String]
$RedirectUri,
[Parameter(Mandatory = $true, ParameterSetName = 'Credentials')]
[System.Net.ICredentials]
$UserCredentials,
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
[Parameter(Mandatory = $true, ParameterSetName = 'RedirectUri')]
[Parameter(Mandatory = $true, ParameterSetName = 'Credentials')]
[String]
$ApplicationID,
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
[Parameter(Mandatory = $true, ParameterSetName = 'RedirectUri')]
[Parameter(Mandatory = $true, ParameterSetName = 'Credentials')]
[String]
$Tenant,
[Parameter(Mandatory = $false, ParameterSetName = 'Thumbprint')]
[Parameter(Mandatory = $false, ParameterSetName = 'Certificate')]
[Parameter(Mandatory = $false, ParameterSetName = 'ClientSecret')]
[Parameter(Mandatory = $false, ParameterSetName = 'RedirectUri')]
[Parameter(Mandatory = $false, ParameterSetName = 'Credentials')]
[Parameter(Mandatory = $false, ParameterSetName = 'ManagedIdentity')]
[string]
$Resource = 'https://management.azure.com/.default',
[Parameter(Mandatory = $false)]
[Switch]
$Force,
[Parameter(Mandatory = $false, ParameterSetName = 'ManagedIdentity')]
[Switch]
$ManagedIdentity
)
begin {
if ($Force) {
Write-Verbose 'Connect-Aza: -Force parameter found. Running Disconnect-Aza to force a log on.'
$null = Disconnect-Aza
}
else {
Initialize-AzaConnect
}
if ($Certificate.length -eq 40) {
$Thumbprint = $Certificate
}
}
process {
try {
if ($Thumbprint) {
Write-Verbose "Connect-Aza: Thumbprint: Logging in with Thumbprint."
Receive-AzaOauthToken `
-ApplicationID $ApplicationID `
-Tenant $Tenant `
-Thumbprint $Thumbprint `
-Resource $Resource
}
elseif ($Certificate) {
Write-Verbose "Connect-Aza: Certificate: Logging in with certificate."
Receive-AzaOauthToken `
-ApplicationID $ApplicationID `
-Tenant $Tenant `
-Certificate $Certificate `
-Resource $Resource
}
elseif ($ClientSecret) {
Write-Verbose "Connect-Aza: ClientSecret: Logging in with ClientSecret."
Receive-AzaOauthToken `
-ApplicationID $ApplicationID `
-Tenant $Tenant `
-ClientSecret $ClientSecret `
-Resource $Resource
}
elseif ($RedirectUri) {
Write-Verbose "Connect-Aza: MFA UserCredentials: Logging in with MFA UserCredentials."
Receive-AzaOauthToken `
-ApplicationID $ApplicationID `
-Tenant $Tenant `
-RedirectUri $RedirectUri `
-Resource $Resource
}
elseif ($UserCredentials) {
Write-Verbose "Connect-Aza: Basic UserCredentials: Logging in with Basic UserCredentials."
Receive-AzaOauthToken `
-ApplicationID $ApplicationID `
-Tenant $Tenant `
-UserCredentials $UserCredentials `
-Resource $Resource
}
elseif ($PAT) {
$Resource = 'Azure DevOps'
Write-Verbose "Connect-Aza: PAT: Logging in with Personal Access Token (Azure DevOps)."
Receive-AzaOauthToken `
-PAT $PAT
}
elseif ($ManagedIdentity) {
if ($Resource -like "*.default*") {
$Resource = $Resource.Replace('.default', '')
}
Receive-AzaOauthToken `
-Resource $Resource `
-ManagedIdentity 'TryMe'
}
}
catch {
throw $_
}
}
end {
return "You've successfully logged in to $Resource"
}
}
function Disconnect-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Use this to log off Azure Service Management API.
.DESCRIPTION
To update the OauthToken I fill the global scope with a number of properties.
The properties are emptied by Disconnect-Aza.
.EXAMPLE
Disconnect-Aza
#>
[CmdletBinding()]
param (
)
begin {
if ($global:AzaLoginType.length -ge 1) {
Write-Verbose "Disconnect-Aza: Disconnecting from $global:AzaResource."
}
}
process {
try {
$Null = Get-Variable -Name "Aza*" -Scope Global | Remove-Variable -Force -Scope Global
}
catch {
throw $_.Exception.Message
}
}
end {
return "You've successfully logged out."
}
}
function Show-AzaAccessToken {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
You can use this cmdlet to show you the decoded Oauth token.
.DESCRIPTION
Its mainly used for troubleshooting permission errors.
.PARAMETER AccessToken
You can leave this empty unless you want to decode another Oauth token.
.PARAMETER Roles
By using the -Roles switch it will only show you the roles that you have assigned to your App registration.
.EXAMPLE
Show-AzaAccessToken
Show-AzaAccessToken -Roles
#>
[CmdletBinding()]
param (
[parameter(mandatory = $false)]
$AccessToken = ($global:AzaheaderParameters).Authorization,
[parameter(mandatory = $false)]
[switch]
$Roles
)
begin {
try {
if ($AccessToken -like "Bearer *") {
Write-Verbose "Show-AzaAccessToken: begin: Removing 'Bearer ' from token for formatting"
}
$AccessToken = ($AccessToken).Replace('Bearer ', '')
$AccessTokenSplitted = $AccessToken.Split('.')
Write-Verbose "Show-AzaAccessToken: begin: Formatting Header"
$AccessTokenHeader = $AccessTokenSplitted[0].Replace('-', '+').Replace('_', '/')
While ($AccessTokenHeader.Length % 4) {
Write-Verbose "Show-AzaAccessToken: begin: Adding '=' character so we can modulus 4 for Base64 encoding"
$AccessTokenHeader += '='
}
Write-Verbose "Show-AzaAccessToken: begin: Formatting PayLoad"
$AccessTokenPayLoad = $AccessTokenSplitted.Split(".")[1].Replace('-', '+').Replace('_', '/')
While ($AccessTokenPayLoad.Length % 4) {
Write-Verbose "Show-AzaAccessToken: begin: Adding '=' character so we can modulus 4 for Base64 encoding"
$AccessTokenPayLoad += '='
}
}
catch {
throw $_
}
}
process {
try {
Write-Verbose "Show-AzaAccessToken: process: Decoding Header to JSON"
$AccessTokenHeaderJSON = [System.Text.Encoding]::ASCII.GetString([system.convert]::FromBase64String($AccessTokenHeader))
Write-Verbose "Show-AzaAccessToken: process: Decoding PayLoad to JSON"
$AccessTokenPayLoadJSON = [System.Text.Encoding]::ASCII.GetString([system.convert]::FromBase64String($AccessTokenPayLoad))
Write-Verbose "Show-AzaAccessToken: process: Removing last character from Header"
$AccessTokenHeaderUpdated = $AccessTokenHeaderJSON -replace ".$"
Write-Verbose "Show-AzaAccessToken: process: Replacing first character by ',' in PayLoad"
$AccessTokenPayLoadUpdated = $AccessTokenPayLoadJSON -Replace '^.', ','
Write-Verbose "Show-AzaAccessToken: process: Adding PayLoad to Header"
$AccessTokenJson = $AccessTokenHeaderUpdated + $AccessTokenPayLoadUpdated
Write-Verbose "Show-AzaAccessToken: process: Converting from Json to EndResult"
$AccessTokenEndResult = $AccessTokenJson | ConvertFrom-Json
}
catch {
throw $_
}
}
end {
if ($Roles -eq $true) {
Write-Verbose "Show-AzaAccessToken: end: Roles switch found | returning roles only"
return $AccessTokenEndResult.Roles
}
else {
return $AccessTokenEndResult
}
}
}
function Get-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Get-Aza speaks for itself. All you have to provide is the URL.
.DESCRIPTION
You can grab the URL via the browser developer tools, Fiddler, or from the Azure Service Management API docs.
It will automatically use the Next Link when there is one in the returned request.
.PARAMETER URL
The URL to get data from Microsoft Graph.
.PARAMETER Once
If you only want to retrieve data once, you can use the -Once parameter.
.PARAMETER CustomHeader
Use -CustomHeader to add extra headers, after the cmdlet ran it will convert back to original header.
.EXAMPLE
Get-Aza -URL 'https://management.azure.com/subscriptions/81bdb7e0-2010-4c36-ba35-71c560e3b317/resourceGroups/RG-2019/providers/Microsoft.Automation/automationAccounts/AA-2019-01/runbooks/POST-DC-2019-01?api-version=2015-10-31'
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]
$URL,
[Parameter(Mandatory = $false)]
[switch]
$Once,
[Parameter(Mandatory = $false)]
[object]
$CustomHeader
)
begin {
Update-AzaOauthToken
if ($CustomHeader) {
Enable-AzaCustomHeader -CustomHeader $CustomHeader
}
}
process {
try {
Write-Verbose "Get-Aza: Getting results from $URL."
$Result = Invoke-WebRequest -UseBasicParsing -Headers $global:AzaHeaderParameters -Uri $URL -Method get
if ($result.Headers.'Content-Type' -like "application/octet-stream*") {
Write-Verbose "Get-Aza: Result is in Csv format. Converting to Csv and returning end result."
$EndResult = ConvertFrom-Csv -InputObject $Result
}
elseif ($result.Headers.'Content-Type' -like "application/xml*") {
Write-Verbose "Get-Aza: Result is in XML format. Converting to XML and returning end result."
$Content = $Result.Content.Substring(3, $Response.Content.Length - 3)
$XmlToJSon = [Newtonsoft.Json.JsonConvert]::SerializeXmlNode([xml]$Content)
$JsonToObject = ConvertFrom-Json -InputObject $XmlToJson
Write-Warning 'Get-Aza: To see different data types (Object, JSON, XML, Original) use $global:AzaDataType.'
$global:AzaDataType = [PSCustomObject]@{
Object = $JsonToObject
JSON = $XmlToJSon
XML = $Content
OG = $Result
}
$Result = $JsonToObject | Format-Custom -Depth 1000000000
$EndResult = $Result
}
elseif ($result.Headers.'Content-Type' -like "application/json*") {
Write-Verbose "Get-Aza: Result is in JSON format. Converting to JSON."
$Result = ConvertFrom-Json -InputObject $Result
if ($Result.'@odata.nextLink') {
if (!($Once)) {
Write-Verbose "Get-Aza: There is an @odata.nextLink for more output. We will run Get-Aza again with the next data link."
$EndResult = @()
foreach ($Line in ($Result).value) {
$EndResult += $Line
}
While ($Result.'@odata.nextLink') {
Write-Verbose "Get-Aza: There is another @odata.nextLink for more output. We will run Get-Aza again with the next data link."
Update-AzaOauthToken
$Result = (Invoke-WebRequest -UseBasicParsing -Headers $global:AzaHeaderParameters -Uri $Result.'@odata.nextLink' -Method Get).Content | ConvertFrom-Json
foreach ($Line in ($Result).value) {
$EndResult += $Line
}
Write-Verbose "Get-Aza: Count is: $($EndResult.count)."
}
}
else {
$EndResult = @()
foreach ($Line in ($Result).value) {
$EndResult += $Line
}
Write-Verbose 'Get-Aza: Parameter -Once found. Even if there is an @odata.nextLink for more output, we will not extract more data.'
}
}
elseif ($Result.value) {
Write-Verbose "Get-Aza: There is no @odata.nextLink. We will add the data to end result."
$EndResult = $Result.value
}
else {
Write-Verbose "Get-Aza: There is no @odata.nextLink. We will add the data to end result."
$EndResult = $Result
}
}
elseif ($Result.Headers.'Content-Type' -like "text/plain*") {
$EndResult = $Result.Content
}
elseif ($Result.Headers.'content-type' -like "application/x-zip-compressed*") {
Write-Verbose "Get-Aza: Content is of Type application/x-zip-compressed. Returning Bytes. Use Set-Content-Encoding Byte to write Bytes to file"
$EndResult = $Result.Content
}
else {
$EndResult = $Result.Content
Write-Warning "Result is in an unrecognizable format: $([string]$Result.Headers)."
}
}
catch [System.Net.WebException] {
Write-Warning "WebException Error message! This could be due to throttling limit."
$WebResponse = $_.Exception.Response
if ($WebResponse.StatusCode -eq 429) {
[int]$RetryValue = $WebResponse.Headers['Retry-After']
Write-Warning "WebException Error message! Throttling error. Retry-After header value: $($RetryValue) seconds. Sleeping for $($RetryValue + 1)s"
Start-Sleep -Seconds $($RetryValue + 1)
if ($Result.'@odata.nextLink') {
Get-Aza -URL $Result.'@odata.nextLink'
}
else {
Get-Aza -URL $URL
}
}
else {
throw $_.Exception.Message
}
}
catch {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
throw $_.Exception.Message
}
}
end {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
return $EndResult
}
}
function Post-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Post-Aza can be seen as the 'new' Verb.
With this cmdlet you can create objects in Azure.
.PARAMETER URL
URL to 'POST' to.
.PARAMETER InputObject
-InputObject will accept a PSObject or JSON.
.PARAMETER CustomHeader
Use -CustomHeader to add extra headers, after the cmdlet ran it will convert back to original header.
.PARAMETER Put
Use the -Put switch when the method is a Put instead of Post.
.PARAMETER KeepFormat
By default the InputObject is converted to JSON. With the -KeepFormat switch it will keep the original format.
.EXAMPLE
Post-Aza `
-URL 'https://management.azure.com/subscriptions/81bdb7e0-2010-4c36-ba35-71c560e3b317/resourceGroups/RG-2019/providers/Microsoft.Automation/automationAccounts/AA-2019-01/runbooks/New-PUT-PSScript?api-version=2015-10-31' `
-InputObject $InputObject `
-Put
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]
$URL,
[Parameter(Mandatory = $false)]
[object]
$InputObject,
[Parameter(Mandatory = $false)]
[switch]
$Put,
[Parameter(Mandatory = $false)]
[object]
$CustomHeader,
[Parameter(Mandatory = $false)]
[switch]
$KeepFormat
)
begin {
Update-AzaOauthToken
if ($KeepFormat -ne $true) {
$InputObject = ConvertTo-AzaJson -InputObject $InputObject
}
else {
Write-verbose 'Post-Aza: begin: KeepFormat switch found. Data will not be converted to JSON.'
}
if ($CustomHeader) {
Enable-AzaCustomHeader -CustomHeader $CustomHeader
Write-verbose ($global:AzaHeaderParameters | Convertto-Json -Depth 10)
}
}
process {
try {
if ($InputObject) {
if (!($Put -eq $true)) {
Write-Verbose "Post-Aza: Posting InputObject to $global:AzaResource."
$Result = Invoke-RestMethod -Uri $URL -Headers $global:AzaHeaderParameters -Method post -Body $InputObject
}
else {
Write-Verbose "Post-Aza: Putting InputObject to $global:AzaResource."
$Result = Invoke-RestMethod -Uri $URL -Headers $global:AzaHeaderParameters -Method put -Body $InputObject
}
}
else {
if (!($Put -eq $true)) {
$Result = Invoke-RestMethod -Uri $URL -Headers $global:AzaHeaderParameters -Method post
}
else {
$Result = Invoke-RestMethod -Uri $URL -Headers $global:AzaHeaderParameters -Method put
}
}
}
catch [System.Net.WebException] {
Write-Warning "WebException Error message! This could be due to throttling limit."
$WebResponse = $_.Exception.Response
if ($WebResponse.StatusCode -eq 429) {
[int]$RetryValue = $WebResponse.Headers['Retry-After']
Write-Warning "WebException Error message! Throttling error. Retry-After header value: $($RetryValue) seconds. Sleeping for $($RetryValue + 1)s"
Start-Sleep -Seconds $($RetryValue + 1)
$Result = Post-Aza -URL $URL -InputObject $InputObject
}
else {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
throw $_.Exception.Message
}
}
catch {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
throw $_.Exception.Message
}
}
end {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
Write-Verbose "Post-Aza: We've successfully Posted the data to $global:AzaResource."
return $Result
}
}
function Put-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Put-Aza can be seen as the 'new' Verb.
With this cmdlet you can create objects in Azure.
.PARAMETER URL
URL to 'PUT' to.
.PARAMETER InputObject
-InputObject will accept a PSObject or JSON.
.PARAMETER CustomHeader
Use -CustomHeader to add extra headers, after the cmdlet ran it will convert back to original header.
.PARAMETER KeepFormat
By default the InputObject is converted to JSON. With the -KeepFormat switch it will keep the original format.
.EXAMPLE
$CustomHeader = @{
'x-ms-blob-type' = 'BlockBlob'
'content-type' = 'application/octet-stream'
}
$StorageAccount = 'baswijdenes'
$Container = 'testblob'
$Blob = 'cert.cer'
#$Test = Get-Content C:\Temp\10days.cer -Raw
$test = [System.IO.File]::OpenRead('C:\Temp\10days.cer')
$URL = 'https://{0}.blob.core.windows.net/{1}/{2}' -f $StorageAccount, $Container, $blob
Put-Aza -URL $URL -CustomHeader $CustomHeader -InputObject $test -KeepFormat -Verbose
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]
$URL,
[Parameter(Mandatory = $false)]
[object]
$InputObject,
[Parameter(Mandatory = $false)]
[object]
$CustomHeader,
[Parameter(Mandatory = $false)]
[switch]
$KeepFormat
)
begin {
Write-Verbose 'Put-Aza: begin: Put-Aza uses Post-Aza in the backend.'
$Splatting = @{
URL = $URL
Put = $true
}
if ($InputObject) {
$Splatting.Add('InputObject', $InputObject)
}
if ($CustomHeader) {
$Splatting.Add('CustomHeader', $CustomHeader)
}
if ($KeepFormat) {
$Splatting.Add('KeepFormat', $KeepFormat)
}
}
process {
try {
Post-Aza @Splatting
<# if ($InputObject) {
if ($CustomHeader) {
$Result = Post-Aza -URL $URL -InputObject $InputObject -put -CustomHeader $CustomHeader
}
else {
$Result = Post-Aza -URL $URL -InputObject $InputObject -put
}
}
else {
if ($CustomHeader) {
$Result = Post-Aza -URL $URL -Put -CustomHeader $CustomHeader
}
else {
$Result = Post-Aza -URL $URL -Put
}
}
#>
}
catch {
throw $_.Exception.Message
}
}
end {
# return $Result
}
}
function Patch-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Patch-Aza can be seen as the 'Update' Verb.
In the below example I change the description of a runbook in Azure Automation.
.PARAMETER URL
URL to 'PATCH' to.
.PARAMETER InputObject
-InputObject will accept a PSObject or JSON.
.PARAMETER CustomHeader
Use -CustomHeader to add extra headers, after the cmdlet ran it will convert back to original header.
.EXAMPLE
$InputObject = [PSCustomObject]@{
properties = [PSCustomObject]@{
description = 'Update description with Patch-Aza'
}
}
Patch-Aza `
-URL 'https://management.azure.com/subscriptions/81bdb7e0-2010-4c36-ba35-71c560e3b317/resourceGroups/RG-2019/providers/Microsoft.Automation/automationAccounts/AA-2019-01/runbooks/New-PUT-PSScript?api-version=2015-10-31' `
-InputObject $InputObject
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]
$URL,
[Parameter(Mandatory = $true)]
[object]
$InputObject,
[Parameter(Mandatory = $false)]
[object]
$CustomHeader
)
begin {
Update-AzaOauthToken
$ValidateJson = ConvertTo-AzaJson -InputObject $InputObject -Validate
if ($CustomHeader) {
Enable-AzaCustomHeader -CustomHeader $CustomHeader
}
}
process {
try {
$InputObject = ConvertTo-AzaJson -InputObject $InputObject
Write-Verbose "Patch-Aza: Patching InputObject to $global:AzaResource."
$Result = Invoke-RestMethod -Uri $URL -Headers $global:AzaHeaderParameters -Method Patch -Body $InputObject
}
catch [System.Net.WebException] {
Write-Warning "WebException Error message! This could be due to throttling limit."
$WebResponse = $_.Exception.Response
if ($WebResponse.StatusCode -eq 429) {
[int]$RetryValue = $WebResponse.Headers['Retry-After']
Write-Warning "WebException Error message! Throttling error. Retry-After header value: $($RetryValue) seconds. Sleeping for $($RetryValue + 1)s"
Start-Sleep -Seconds $($RetryValue + 1)
$Result = Patch-Aza -URL $URL -InputObject $InputObject
}
else {
throw $_.Exception.Message
}
}
catch {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
throw $_.Exception.Message
}
}
end {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
Write-Verbose "Patch-Aza: We've successfully Patched the data to $global:AzaResource."
return $Result
}
}
function Delete-Aza {
<#
.LINK
https://github.com/baswijdenes/Optimized.Aza/tree/main
.SYNOPSIS
Delete speaks for itself.
With this cmdlet you can remove objects from Azure.
.PARAMETER URL
-URL is the URL for the item to delete.
.PARAMETER InputObject
-InputObject will accept a PSObject or JSON.
.PARAMETER CustomHeader
Use -CustomHeader to add extra headers, after the cmdlet ran it will convert back to original header.
.EXAMPLE
Delete-Aza `
-URL 'https://management.azure.com/subscriptions/81bdb7e0-2010-4c36-ba35-71c560e3b317/resourceGroups/RG-2019/providers/Microsoft.Automation/automationAccounts/AA-2019-01/runbooks/New-PUT-PSScript?api-version=2015-10-31'
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, Position = 0)]
[string]
$URL,
[Parameter(Mandatory = $false)]
[string]
$InputObject,
[Parameter(Mandatory = $false)]
[object]
$CustomHeader
)
begin {
Update-AzaOauthToken
if ($CustomHeader) {
Enable-AzaCustomHeader -CustomHeader $CustomHeader
}
}
process {
try {
if ($InputObject) {
Write-Verbose "Delete-Aza: Deleting InputObject on $URL to $global:AzaResource."
$InputObject = ConvertTo-AzaJson -InputObject $InputObject
$Result = Invoke-RestMethod -Uri $URL -body $InputObject -Headers $global:AzaHeaderParameters -Method Delete
}
else {
Write-Verbose "Delete-Aza: Deleting conent on $URL to $global:AzaResource."
$Result = Invoke-RestMethod -Uri $URL -Headers $global:AzaHeaderParameters -Method Delete
}
}
catch [System.Net.WebException] {
Write-Warning "WebException Error message! This could be due to throttling limit."
$WebResponse = $_.Exception.Response
if ($WebResponse.StatusCode -eq 429) {
[int]$RetryValue = $WebResponse.Headers['Retry-After']
Write-Warning "WebException Error message! Throttling error. Retry-After header value: $($RetryValue) seconds. Sleeping for $($RetryValue + 1)s"
Start-Sleep -Seconds $($RetryValue + 1)
if ($InputObject) {
$Result = Delete-Aza -URL $URL -InputObject $InputObject
}
else {
$Result = Delete-Aza -URL $URL
}
}
else {
throw $_.Exception.Message
}
}
catch {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
throw $_.Exception.Message
}
}
end {
if ($CustomHeader) {
Disable-AzaCustomHeader
}
Write-Verbose "Delete-Aza: We've successfully deleted the data on $global:AzaResource."
return $Result
}
}
#endregion main
#region internal
function Initialize-AzaConnect {
[CmdletBinding()]
param (
)
if ($global:AzaLoginType.length -ge 1) {
Write-Verbose "Initialize-AzaConnect: You're already logged on."
$Confirmation = Read-Host 'You already logged on. Are you sure you want to proceed? Type (Y)es to continue.'
if (($Confirmation -eq 'y') -or ($Confirmation -eq 'yes') -or ($Confirmation -eq 'true') -or ($Confirmation -eq '(Y)es')) {
Write-Verbose "Initialize-AzaConnect: We will continue logging in."
$null = Disconnect-Aza
}
else {
Write-Verbose "Initialize-AzaConnect: Aborting log in."
throw 'Login aborted.'
}
}
}
function Update-AzaOauthToken {
[CmdletBinding()]
param (
)
if ($null -ne $global:AzaAppPass) {
Receive-AzaOauthToken `
-ApplicationID $global:AzaApplicationID `
-Tenant $global:AzaTenant `
-ClientSecret $global:AzaSecret `
-Resource $($global:AzaResource)
}
elseif ($null -ne $global:AzaCert) {
Receive-AzaOauthToken `
-ApplicationID $global:AzaApplicationID `
-Tenant $global:AzaTenant `
-Certificate $global:AzaCertificate `
-Resource $($global:AzaResource)
}
elseif ($null -ne $global:AzaTPrint) {
Receive-AzaOauthToken `
-ApplicationID $global:AzaApplicationID `
-Tenant $global:AzaTenant `
-Thumbprint $global:AzaThumbprint `
-Resource $($global:AzaResource)
}
elseif ($null -ne $global:AzaRU) {
Receive-AzaOauthToken `
-ApplicationID $global:AzaApplicationID `
-Tenant $global:AzaTenant `
-RedirectUri $global:AzaRedirectUri `
-Resource $($global:AzaResource)
}
elseif ($null -ne $global:AzaBasic) {
Receive-AzaOauthToken `
-ApplicationID $global:AzaApplicationID `
-Tenant $global:AzaTenant `
-UserCredentials $global:AzaUserCredentials `
-Resource $($global:AzaResource)
}
elseif ($null -ne $global:AzaPAT) {
}
elseif ($null -ne $global:AzaManagedIdentity) {
Receive-AzaOauthToken `
-ManagedIdentity $global:AzaManagedIdentityType `
-Resource $global:AzaResource
}
else {
Throw "You need to run Connect-Aza before you can continue. Exiting script..."
}
}
function Receive-AzaOauthToken {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
[string]
$Thumbprint,
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
$Certificate,
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
$ClientSecret,
[Parameter(Mandatory = $true, ParameterSetName = 'PAT')]
$PAT,
[Parameter(Mandatory = $true, ParameterSetName = 'ManagedIdentity')]
[string]
$ManagedIdentity,
[Parameter(Mandatory = $true, ParameterSetName = 'Redirecturi')]
[string]
$RedirectUri,
[Parameter(Mandatory = $true, ParameterSetName = 'UserCredentials')]
[System.Net.ICredentials]
$UserCredentials,
[Parameter(Mandatory = $true, ParameterSetName = 'UserCredentials')]
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
[Parameter(Mandatory = $true, ParameterSetName = 'Redirecturi')]
[Parameter(Mandatory = $true, ParameterSetName = 'ManagedIdentity')]
$Resource,
[Parameter(Mandatory = $true, ParameterSetName = 'UserCredentials')]
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
[Parameter(Mandatory = $true, ParameterSetName = 'Redirecturi')]
[string]
$ApplicationID,
[Parameter(Mandatory = $true, ParameterSetName = 'UserCredentials')]
[Parameter(Mandatory = $true, ParameterSetName = 'Thumbprint')]
[Parameter(Mandatory = $true, ParameterSetName = 'Certificate')]
[Parameter(Mandatory = $true, ParameterSetName = 'ClientSecret')]
[Parameter(Mandatory = $true, ParameterSetName = 'Redirecturi')]
[string]
$Tenant
)
begin {
try {
$global:AzaResource = $Resource
[System.Collections.Generic.List[String]]$Resource = @($($Resource))
if ($null -eq $PAT) {
$global:AzaTenant = $Tenant
$global:AzaApplicationID = $ApplicationID
}
[datetime]$UnixDateTime = '1970-01-01 00:00:00'
$Date = Get-Date
$UTCDate = [System.TimeZoneInfo]::ConvertTimeToUtc($Date)
if ($thumbprint.length -gt 5) {
Write-Verbose "Receive-AzaOauthToken: Certificate: We will continue logging in with Certificate."
if (($null -eq $global:AzaTPCertificate) -or ($Thumbprint -ne ($global:AzaTPCertificate).Thumbprint)) {
Write-Verbose "Receive-AzaOauthToken: Certificate: Starting search in CurrentUser\my."
$TPCertificate = Get-Item Cert:\CurrentUser\My\$Thumbprint -ErrorAction SilentlyContinue
if ($null -eq $TPCertificate) {
Write-Verbose "Receive-AzaOauthToken: Certificate not found in CurrentUser. Continuing in LocalMachine\my."
$TPCertificate = Get-Item Cert:\localMachine\My\$Thumbprint -ErrorAction SilentlyContinue
}
if ($null -eq $TPCertificate) {
throw "We did not find a certificate under: $Thumbprint. Exiting script..."
}
}
else {
$TPCertificate = $global:AzaTPCertificate
Write-Verbose "Receive-AzaOauthToken: Certificate: We already obtained a certificate from a previous login. We will continue logging in."
}