-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzDOPSSample.ps1
More file actions
465 lines (399 loc) · 15.9 KB
/
AzDOPSSample.ps1
File metadata and controls
465 lines (399 loc) · 15.9 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
<#
.SYNOPSIS
Azure DevOps PowerShell Sample
.DESCRIPTION
Quick start sample for creating PowerShell scripts targeting Azure DevOps Server/Services.
.PARAMETER ServiceUri
Provide the URI of the Azure DevOps Services organization or Azure DevOps Server collection you want to work on.
.PARAMETER Quiet
Specify this switch to suppress confirmation prompts.
.PARAMETER GetCredentials
Specify this switch if you need to use special credentials when connecting to your Azure DevOps Server.
.PARAMETER UsePAT
Specify this switch if you need to provide a Personal Access Token to connect your Azure DevOps Server/Services.
.PARAMETER AllowHttp
Specify this switch if you need connect to Azure DevOps over unencrypted http (not https).
.PARAMETER MaxRestCallRetries
Provide the number of retries for failing REST calls. In general, you shouldn't need this option. However, when running in an
unstable environment (e.g., unreliable network connection), retries can help by automatically rerunning failing REST calls.
.PARAMETER TraceErrors
Specify this switch to enabled extended error tracing using netsh. If you combine this with the MaxRestCallRetries parameter,
only the last retry is traced. Otherwise, every request is trace, but traces for succeeding network calls are deleted for security reasons.
Note: You need to run the script as a local administrator when using this switch. Otherwise, network tracing is not allowed.
.EXAMPLE
.\AzDOPSSample.ps1 -ServiceUri http://MyTfs:8080/tfs/DefaultCollection -GetCredentials
Runs the script on the DefaultCollection of your local Azure DevOps Server using Windows credentials.
.EXAMPLE
.\AzDOPSSample.ps1 -ServiceUri https://dev.azure.com/myOrg -Quiet -UsePAT
Runs the script on the Azure DevOps Services organization myOrg, suppressing confirmations and using a PAT for authentication.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, HelpMessage="Enter the URI of the Azure DevOps Services organization or Azure DevOps Server collection you want to work on.")]
[ValidateNotNullOrEmpty()]
[string]$ServiceUri,
# You should add your additional script parameters here.
[Parameter(Mandatory=$false, HelpMessage="Specify this switch to suppress confirmation prompts.")]
[switch]$Quiet,
[Parameter(Mandatory=$false, HelpMessage="Specify this switch if you need to use special credentials when connecting to your Azure DevOps Server.")]
[switch]$GetCredentials,
[Parameter(Mandatory=$false, HelpMessage="Specify this switch if you need to provide a Personal Access Token to connect your Azure DevOps Server/Services.")]
[switch]$UsePAT,
[Parameter(Mandatory=$false, HelpMessage="Specify this switch if you need connect to Azure DevOps over unencrypted http (not https).")]
[switch]$AllowHttp,
[Parameter(Mandatory=$false, HelpMessage="Provide the number of retries for failing REST calls. In general, you shouldn't need this option.")]
[int]$MaxRestCallRetries = 1,
[Parameter(Mandatory=$false, HelpMessage="Specify this switch to enable extended error tracing using netsh.")]
[switch]$TraceErrors
)
################################################################################
# Configuration section
# Put general configuration stuff and validations here
################################################################################
#Requires -Version 6.2
Set-StrictMode -Version 3.0
$scriptName = "Azure DevOps PowerShell Sample"
# Use semantic versioning here
$version = "0.0.1"
$year = "2020"
$Global:quietAnswer = $true
$Global:defaultAnswer = $false
$RestCallRetryDelayInSeconds = 2
function Test-Parameters()
{
$validationResult = $true;
Write-Host " Service: $ServiceUri" -NoNewline
if (!([System.Uri]::IsWellFormedUriString($ServiceUri, [System.UriKind]::Absolute)))
{
Write-Host " (invalid)" -ForegroundColor Red -NoNewline
$validationResult = $false
}
Write-Host
# Add your own parameters and parameter validations here
Write-Host "Authentication: $(if ($UsePAT) { "PAT" } elseif ($GetCredentials) { "Custom Credentials" } else { "Default Credentials" })"
Write-Host " Allow HTTP: $AllowHttp"
$Global:isQuiet = $Quiet
Write-Host " Quiet: $Quiet"
Write-Host " Max Retries: $MaxRestCallRetries" -NoNewline
if ($MaxRestCallRetries -lt 1) {
Write-Host " (invalid)" -ForegroundColor Red -NoNewline
$validationResult = $false;
}
Write-Host
Write-Host " Trace Errors: $TraceErrors"
Write-Host "--------------------------------------------------------------------------------"
return $validationResult
}
################################################################################
# Helper functions
################################################################################
function Write-Header()
{
Write-Host "--------------------------------------------------------------------------------"
Write-Host "$scriptName - v$version"
Write-Host "Copyright (c) $year Microsoft Premier Services - Microsoft Deutschland GmbH"
Write-Host "--------------------------------------------------------------------------------"
}
function Write-SimpleError($message)
{
Write-Host $message -ForegroundColor red -BackgroundColor black
}
function Exit-WithError($message, $exitCode)
{
Write-SimpleError $message
exit $exitCode
}
function Get-Consent([string] $message)
{
if ($Global:isQuiet)
{
return $Global:quietAnswer
}
Write-Host "$message"
if ($Global:defaultAnswer) {
Write-Host "[Y] Yes" -ForegroundColor Yellow -NoNewline
Write-Host " [A] Yes to All [N] No [L] No to All (default is `"Y`"): " -NoNewline
}
else
{
Write-Host "[Y] Yes [A] Yes to All " -NoNewline
Write-Host "[N] No" -ForegroundColor Yellow -NoNewline
Write-Host " [L] No to All (default is `"N`"): " -NoNewline
}
switch (Read-Host)
{
"y" { $true }
"a" { $Global:quietAnswer = $true; $Global:isQuiet = $true; return $true }
"n" { return $false }
"l" { $Global:quietAnswer = $false; $Global:isQuiet = $true; return $false }
default { return $Global:defaultAnswer }
}
}
function Get-SpecialConsent([string] $message)
{
Write-Host "$message" -ForegroundColor Red
if ($Global:defaultAnswer) {
Write-Host "[Y] Yes" -ForegroundColor Yellow -NoNewline
Write-Host " [N] No (default is `"Y`"): " -NoNewline
}
else
{
Write-Host "[Y] Yes " -NoNewline
Write-Host "[N] No" -ForegroundColor Yellow -NoNewline
Write-Host " (default is `"N`"): " -NoNewline
}
switch (Read-Host)
{
"y" { $true }
"n" { return $false }
default { return $Global:defaultAnswer }
}
}
function Get-Encoding($encodingString)
{
switch($encodingString.ToLower())
{
"ascii" { return [System.Text.Encoding]::ASCII }
"unicode" { return [System.Text.Encoding]::Unicode }
"utf7" { return [System.Text.Encoding]::UTF7 }
"utf8" { return [System.Text.Encoding]::UTF8 }
"utf32" { return [System.Text.Encoding]::UTF32 }
}
}
function ConvertTo-Base64String
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline)]
[string] $InputString,
[ValidateSet("ascii", "unicode", "utf7", "utf8", "utf32")]
[string] $Encoding
)
Process {
$enc = Get-Encoding $Encoding
$bytes = $enc.GetBytes($inputString)
return [System.Convert]::ToBase64String($bytes)
}
}
Function ConvertFrom-Base64String
{
[CmdletBinding()]
Param (
[Parameter(ValueFromPipeline)]
[string] $InputString,
[ValidateSet("ascii", "unicode", "utf7", "utf8", "utf32")]
[string] $Encoding
)
Process {
$enc = Get-Encoding $Encoding
$bytes = [System.Convert]::FromBase64String($inputString)
return $enc.GetString($bytes)
}
}
function Test-Elevation()
{
# https://gist.github.com/jhochwald/46014a3de425dc21c1f1f7e31cd49cf1
return ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')
}
function Assert-Preconditions()
{
Write-Header
if (!(Test-Parameters)) { Exit-WithError "One or more input parameters are invalid. Aborting." -1 }
Get-HttpHeadersAndCredentials
}
################################################################################
# REST call functions
################################################################################
# HTTP Headers
$Global:headers = @{}
$Global:credentials = $null
function Get-HttpHeadersAndCredentials()
{
$Global:headers = @{ Accept="application/json" }
$Global:headers["Accept-Charset"] = "utf-8"
if ($UsePAT)
{
$PAT = Read-Host "Enter PAT" -AsSecureString
$patString = "pat:$([System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PAT)))"
$Global:headers["Authorization"] = "Basic $(ConvertTo-Base64String -InputString $patString -Encoding ascii)"
}
if ($GetCredentials)
{
$Global:credentials = Get-Credential
}
}
function Get-ErrorForWebException([System.Net.Http.HttpRequestException] $Exception, [string] $reqBody)
{
try
{
# see https://stackoverflow.com/questions/35986647/how-do-i-get-the-body-of-a-web-request-that-returned-400-bad-request-from-invoke
$respStream = $Exception.Response.GetResponseStream()
$respStream.Position = 0
$reader = New-Object System.IO.StreamReader($respStream)
$respBody = $reader.ReadToEnd()
$respStatusCode = $Exception.Response.StatusCode
$respStatusCodeInt = [System.Convert]::ToInt32($respStatusCode)
return "Status Code $respStatusCode ($respStatusCodeInt): $respBody `n $reqBody"
}
catch
{
return $(if ($Exception) { $Exception.ToString() } else { "Unknown Error." })
}
}
function Invoke-RestGet($uri, [ref]$responseHeader)
{
Invoke-Rest $uri "Get" ([ref]$responseHeader)
}
function Invoke-RestPost($uri, $body, [ref]$responseHeader)
{
if ($null -eq $body) {
Invoke-Rest $uri "Post" ([ref]$responseHeader)
} else {
Invoke-RestWithBody $uri "Post" $body ([ref]$responseHeader)
}
}
function Invoke-RestPut($uri, $body, [ref]$responseHeader)
{
if ($null -eq $body) {
Invoke-Rest $uri "Put" ([ref]$responseHeader)
} else {
Invoke-RestWithBody $uri "Put" $body ([ref]$responseHeader)
}
}
function Invoke-RestPatch($uri, $body, [ref]$responseHeader)
{
if ($null -eq $body) {
Invoke-Rest $uri "Patch" ([ref]$responseHeader)
} else {
Invoke-RestWithBody $uri "Patch" $body ([ref]$responseHeader)
}
}
function Invoke-RestDelete($uri, [ref]$responseHeader)
{
Invoke-Rest $uri "Delete" ([ref]$responseHeader)
}
function Invoke-RestOptions($uri, [ref]$responseHeader)
{
Invoke-Rest $uri "Options" ([ref]$responseHeader)
}
function Invoke-RestWithRetriesAndTracing($uri, $method, $body = $null, [ref]$responseHeader)
{
$success = $false
$tries = 0
$delaySeconds = $RestCallRetryDelayInSeconds
while (-not $success -and $tries -lt $MaxRestCallRetries)
{
$isLastTry = ($tries -eq ($MaxRestCallRetries - 1))
if ($isLastTry -and $TraceErrors)
{
if (Test-Elevation)
{
$traceFilePath = [System.IO.Path]::Combine($env:TEMP, "Invoke-Rest$method-$((Get-Date).Ticks.ToString()).etl")
Write-Host "Tracing last try for $uri at $traceFilePath..."
Invoke-Command -ScriptBlock {netsh trace start persistent=yes capture=yes tracefile="$traceFilePath"}
}
else
{
Write-Warning "Cannot create a network trace for communication with URI $uri. Please run the script as local administrator."
}
}
$tries += 1
try
{
if ($null -eq $body)
{
$result = Invoke-Rest $uri $method ([ref]$responseHeaderValue)
}
else
{
$result = Invoke-RestWithBody $uri $method $body ([ref]$responseHeaderValue)
}
$success = $true
}
catch
{
if ($_.Exception.GetType().FullName -eq "System.Net.Http.HttpRequestException")
{
$exceptionMessage = GetErrorForWebException -Exception $_.Exception
}
else
{
$exceptionMessage = $_.Exception.Message
}
$message = "Call failed with $exceptionMessage."
if ($isLastTry)
{
Exit-WithError $message 1
}
else
{
Write-Warning $message
Write-Host "Retrying after $delaySeconds seconds..." -ForegroundColor Yellow
Start-Sleep -Seconds $delaySeconds
$delaySeconds *= 2 # Exponential Backoff
}
}
finally
{
if ($isLastTry -and $TraceErrors -and (Test-Elevation)) {
Write-Host "Finishing network trace. This will take a while... Please do not interrupt!"
Invoke-Command -ScriptBlock {netsh trace stop}
if ($success)
{
Remove-Item $traceFilePath
}
}
}
}
return $result
}
function Invoke-Rest($uri, $method, [ref]$responseHeader)
{
$responseHeaderValue = @{}
if ($UsePAT)
{
return Invoke-RestMethod $uri -Method $method -Headers $Global:headers -ResponseHeadersVariable "responseHeaderValue" -AllowUnencrypted:$AllowHttp
}
elseif ($GetCredentials)
{
return Invoke-RestMethod $uri -Method $method -Headers $Global:headers -Credential $Global:credentials -ResponseHeadersVariable "responseHeaderValue" -AllowUnencrypted:$AllowHttp
}
else
{
return Invoke-RestMethod $uri -Method $method -Headers $Global:headers -UseDefaultCredentials -ResponseHeadersVariable "responseHeaderValue" -AllowUnencrypted:$AllowHttp
}
if ($responseHeader) {
$responseHeader.Value = $responseHeaderValue
}
}
function Invoke-RestWithBody($uri, $method, $body, [ref]$responseHeader)
{
$jsonBody = ConvertTo-Json $body -Depth 100 -Compress
$jsonBody = $jsonBody.Replace("\u0026", "&")
$responseHeaderValue = @{}
if ($UsePAT)
{
return Invoke-RestMethod $uri -Method $method -Headers $Global:headers -ContentType "application/json" -Body ([System.Text.Encoding]::UTF8.GetBytes($jsonBody)) -ResponseHeadersVariable "responseHeaderValue" -AllowUnencrypted:$AllowHttp
}
elseif ($GetCredentials)
{
return Invoke-RestMethod $uri -Method $method -Headers $Global:headers -ContentType "application/json" -Body ([System.Text.Encoding]::UTF8.GetBytes($jsonBody)) -Credential $Global:credentials -ResponseHeadersVariable "responseHeaderValue" -AllowUnencrypted:$AllowHttp
}
else
{
return Invoke-RestMethod $uri -Method $method -Headers $Global:headers -ContentType "application/json" -Body ([System.Text.Encoding]::UTF8.GetBytes($jsonBody)) -UseDefaultCredentials -ResponseHeadersVariable "responseHeaderValue" -AllowUnencrypted:$AllowHttp
}
if ($responseHeader) {
$responseHeader.Value = $responseHeaderValue
}
}
################################################################################
# Business logic functions
################################################################################
################################################################################
# Main script starts here
################################################################################
# Do not remove this!
Assert-Preconditions
# Write your business logic here
Write-Warning "This is just a sample. Don't expect it to do anyting! :-)"