-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathcommon.ps1
More file actions
1262 lines (1033 loc) · 40.1 KB
/
common.ps1
File metadata and controls
1262 lines (1033 loc) · 40.1 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
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
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "It is used in other files")]
$profilesPath = "$HOME/vsteam_profiles.json"
# This is the main function for calling TFS and VSTS. It handels the auth and format of the route.
# If you need to call TFS or VSTS this is the function to use.
function _callAPI {
[CmdletBinding()]
param(
[string]$resource,
[string]$area,
[string]$id,
[string]$version,
[string]$subDomain,
[ValidateSet('Get', 'Post', 'Patch', 'Delete', 'Options', 'Put', 'Default', 'Head', 'Merge', 'Trace')]
[string]$method,
[Parameter(ValueFromPipeline = $true)]
[object]$body,
[string]$InFile,
[string]$OutFile,
[string]$ContentType,
[string]$ProjectName,
[string]$Team,
[string]$Url,
[object]$QueryString,
[hashtable]$AdditionalHeaders = @{ },
# Name of the output variable that will content the response headers
# Specify the name of the variable without the $ prefix
[string]$ResponseHeadersVariable,
# Some API calls require the Project ID and not the project name.
# However, the dynamic project name parameter only shows you names
# and not the Project IDs. Using this flag the project name provided
# will be converted to the Project ID when building the URI for the API
# call.
[switch]$UseProjectId,
# This flag makes sure that even if a default project is set that it is
# not used to build the URI for the API call. Not all API require or
# allow the project to be used. Setting a default project would cause
# that project name to be used in building the URI that would lead to
# 404 because the URI would not be correct.
[Alias('IgnoreDefaultProject')]
[switch]$NoProject,
# This flag makes sure that no specific account is used
# some APIs do not have an account in their API uri because
# they are not account specific in the url path itself. (e.g. user profile, pipeline billing)
[switch]$NoAccount,
[ValidateSet('None', 'Header', 'Body')]
[string]$UseContinuationToken = 'None',
# Allows to specify a header or continuation token property different of the default values.
# If this parameter is not specified, the default value is X-MS-ContinuationToken or continuationToken
# depending if $UseHeader is present or not, respectively. Ignored if $UseContinuationToken -eq 'None'
[string]$ContinuationTokenName,
# Number of pages to be retrieved. If 0, or not specified, it will return all the available pages.
# Ignored if $UseContinuationToken -eq 'None'
[int]$MaxPages = 0,
# When using continuationToken, it is neccesary expand a specific property to get the real
# collection of objects. Ignored if $UseContinuationToken -eq 'None'
[string]$CollectionPropertyName
)
process {
# If the caller did not provide a Url build it.
if (-not $Url) {
$buildUriParams = @{ } + $PSBoundParameters;
$extra = 'method', 'body', 'InFile', 'OutFile', 'ContentType', 'AdditionalHeaders'
foreach ($x in $extra) { $buildUriParams.Remove($x) | Out-Null }
$Url = _buildRequestURI @buildUriParams
}
elseif ($QueryString) {
# If the caller provided the URL and QueryString we need
# to add the querystring now
foreach ($key in $QueryString.keys) {
$Url += _appendQueryString -name $key -value $QueryString[$key]
}
}
if ($body) {
Write-Verbose "Body $body"
}
$params = $PSBoundParameters
$params.Add('Uri', $Url)
$params.Add('UserAgent', (_getUserAgent))
$params.Add('TimeoutSec', (_getDefaultTimeout))
# always use utf8 and json as default content type instead of xml
if ($false -eq $PSBoundParameters.ContainsKey("ContentType")) {
$params.Add('ContentType', 'application/json; charset=utf-8')
}
# do not use header when requested. Then bearer must be provided with additional headers
$params.Add('Headers', @{ })
# configure continuationToken management
if ($UseContinuationToken -ne 'None' -and [string]::IsNullOrEmpty($ContinuationTokenName)) {
if ($UseContinuationToken -eq 'Body') {
$ContinuationTokenName = 'continuationToken'
} else {
$ContinuationTokenName = 'X-MS-ContinuationToken'
}
}
if ($UseContinuationToken -eq 'Header') {
$params.Add('ResponseHeadersVariable', 'ResponseHeaders')
}
# checking if an authorization token is provided already with the additional headers
# use case: sometimes other tokens for certain APIs have to be used (buying pipelines) in order to work
# some parts of internal APIs use their own token based on the PAT
if (!$AdditionalHeaders.ContainsKey("Authorization")) {
if (_useWindowsAuthenticationOnPremise) {
$params.Add('UseDefaultCredentials', $true)
}
elseif (_useBearerToken) {
$params['Headers'].Add("Authorization", "Bearer $env:TEAM_TOKEN")
}
else {
$params['Headers'].Add("Authorization", "Basic $env:TEAM_PAT")
}
}
if ($AdditionalHeaders -and $AdditionalHeaders.PSObject.Properties.name -match "Keys") {
foreach ($key in $AdditionalHeaders.Keys) {
$params['Headers'].Add($key, $AdditionalHeaders[$key])
}
}
# We have to remove any extra parameters not used by Invoke-RestMethod
$extra = 'NoAccount', 'NoProject', 'UseProjectId', 'Area', 'Resource', 'SubDomain', 'Id', 'Version', 'JSON', 'ProjectName',
'Team', 'Url', 'QueryString', 'AdditionalHeaders', 'CustomBearer', 'UseContinuationToken', 'ContinuationTokenName',
'MaxPages', 'CollectionPropertyName'
foreach ($e in $extra) { $params.Remove($e) | Out-Null }
$page = 0
$obj = @()
$requestUri = $params['Uri']
do {
try {
$resp = Invoke-RestMethod @params
if ($resp) {
Write-Verbose "return type: $($resp.gettype())"
Write-Verbose $resp
}
if ($UseContinuationToken -eq 'Body') {
$continuationToken = $resp."$ContinuationTokenName"
$continuationToken = [uri]::EscapeDataString($continuationToken)
$params['Uri'] = "${requestUri}&continuationToken=$continuationToken"
$obj += $resp."$CollectionPropertyName"
} elseif ($UseContinuationToken -eq 'Header') {
$continuationToken = $ResponseHeaders[$ContinuationTokenName]
$params['Uri'] = "${requestUri}&continuationToken=$continuationToken"
$obj += $resp."$CollectionPropertyName"
} else {
return $resp
}
$page++
Write-Verbose "page $page"
}
catch {
_handleException $_
throw
}
} while (-not [string]::IsNullOrEmpty($continuationToken) -and $i -lt $MaxPages)
return $obj
}
}
# Not all versions support the name features.
function _supportsGraph {
_hasAccount
if ($false -eq $(_testGraphSupport)) {
throw 'This account does not support the graph API.'
}
}
function _testGraphSupport {
(_getApiVersion Graph) -as [boolean]
}
function _supportsHierarchyQuery {
_hasAccount
if ($false -eq $(_testHierarchyQuerySupport)) {
throw 'This account does not support the hierarchy query API.'
}
}
function _testHierarchyQuerySupport {
(_getApiVersion HierarchyQuery) -as [boolean]
}
function _supportsBilling {
_hasAccount
if ($false -eq $(_testBillingSupport)) {
throw 'This account does not support the billing API.'
}
}
function _testBillingSupport {
(_getApiVersion Billing) -as [boolean]
}
function _supportVariableGroups {
_hasAccount
if ($false -eq $(_testVariableGroupsSupport)) {
throw 'This account does not support the variable groups.'
}
}
function _testVariableGroupsSupport {
(_getApiVersion VariableGroups) -as [boolean]
}
function _supportsSecurityNamespace {
_hasAccount
if (([vsteam_lib.Versions]::Version -ne "VSTS") -and ([vsteam_lib.Versions]::Version -ne "AzD")) {
throw 'Security Namespaces are currently only supported in Azure DevOps Service (Online)'
}
}
function _supportsMemberEntitlementManagement {
[CmdletBinding(DefaultParameterSetName="upto")]
param(
[parameter(ParameterSetName="upto")]
[string]$UpTo = $null,
[parameter(ParameterSetName="onwards")]
[string]$Onwards = $null
)
_hasAccount
$apiVer = _getApiVersion MemberEntitlementManagement
if (-not $apiVer) {
throw 'This account does not support Member Entitlement.'
} elseif (-not [string]::IsNullOrEmpty($UpTo) -and $apiVer -gt $UpTo) {
throw "EntitlementManagemen version must be equal or lower than $UpTo for this call, current value $apiVer"
} elseif (-not [string]::IsNullOrEmpty($Onwards) -and $apiVer -lt $Onwards) {
throw "EntitlementManagemen version must be equal or greater than $Onwards for this call, current value $apiVer"
}
}
function _testAdministrator {
$user = [Security.Principal.WindowsIdentity]::GetCurrent()
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
# When you mock this in tests be sure to add a Parameter Filter that matches
# the Service that should be used.
# Mock _getApiVersion { return '1.0-gitUnitTests' } -ParameterFilter { $Service -eq 'Git' }
# Also test in the Assert-MockCalled that the correct version was used in the URL that was
# built for the API call.
function _getApiVersion {
[CmdletBinding(DefaultParameterSetName = 'Service')]
[OutputType([string])]
param (
[parameter(ParameterSetName = 'Service', Mandatory = $true, Position = 0)]
[ValidateSet('Build', 'Release', 'Core', 'Git', 'DistributedTask',
'DistributedTaskReleased', 'VariableGroups', 'Tfvc',
'Packaging', 'MemberEntitlementManagement',
'ExtensionsManagement', 'ServiceEndpoints', 'Graph',
'TaskGroups', 'Policy', 'Processes', 'HierarchyQuery', 'Pipelines', 'Billing', 'Wiki', 'WorkItemTracking')]
[string] $Service,
[parameter(ParameterSetName = 'Target')]
[switch] $Target
)
if ($Target.IsPresent) {
return [vsteam_lib.Versions]::GetApiVersion("Version")
}
else {
return [vsteam_lib.Versions]::GetApiVersion($Service)
}
}
function _getInstance {
return [vsteam_lib.Versions]::Account
}
function _getDefaultTimeout {
if ($Global:PSDefaultParameterValues["*-vsteam*:vsteamApiTimeout"]) {
return $Global:PSDefaultParameterValues["*-vsteam*:vsteamApiTimeout"]
}
else {
return 60
}
}
function _getDefaultProject {
return $Global:PSDefaultParameterValues["*-vsteam*:projectName"]
}
function _hasAccount {
if (-not $(_getInstance)) {
throw 'You must call Set-VSTeamAccount before calling any other functions in this module.'
}
}
function _buildRequestURI {
[CmdletBinding()]
param(
[string]$team,
[string]$resource,
[string]$area,
[string]$id,
[string]$version,
[string]$subDomain,
[object]$queryString,
[Parameter(Mandatory = $false)]
[vsteam_lib.ProjectValidateAttribute($false)]
$ProjectName,
[switch]$UseProjectId,
[switch]$NoProject,
[switch]$NoAccount
)
process {
_hasAccount
$sb = New-Object System.Text.StringBuilder
$instance = "https://dev.azure.com"
if ($NoAccount.IsPresent -eq $false) {
$instance = _getInstance
}
$sb.Append($(_addSubDomain -subDomain $subDomain -instance $instance)) | Out-Null
# There are some APIs that must not have the project added to the URI.
# However, if they caller set the default project it will be passed in
# here and added to the URI by mistake. Functions that need the URI
# created without the project even if the default project is set needs
# to pass the -NoProject switch.
if ($ProjectName -and $NoProject.IsPresent -eq $false -and $NoAccount.IsPresent -eq $false) {
if ($UseProjectId.IsPresent) {
$projectId = (Get-VSTeamProject -Name $ProjectName | Select-Object -ExpandProperty id)
$sb.Append("/$projectId") | Out-Null
}
else {
$sb.Append("/$projectName") | Out-Null
}
}
if ($team) {
$sb.Append("/$team") | Out-Null
}
$sb.Append("/_apis") | Out-Null
if ($area) {
$sb.Append("/$area") | Out-Null
}
if ($resource) {
$sb.Append("/$resource") | Out-Null
}
if ($id) {
$sb.Append("/$id") | Out-Null
}
if ($version) {
$sb.Append("?api-version=$version") | Out-Null
}
$url = $sb.ToString()
if ($queryString) {
foreach ($key in $queryString.keys) {
$Url += _appendQueryString -name $key -value $queryString[$key]
}
}
return $url
}
}
function _handleException {
param(
[Parameter(Position = 1)]
$ex
)
$handled = $false
if ($ex.Exception.PSObject.Properties.Match('Response').count -gt 0 -and
$null -ne $ex.Exception.Response -and
$ex.Exception.Response.StatusCode -ne "BadRequest") {
$handled = $true
$msg = "An error occurred: $($ex.Exception.Message)"
Write-Warning -Message $msg
}
try {
$e = (ConvertFrom-Json $ex.ToString())
$hasValueProp = $e.PSObject.Properties.Match('value')
if (0 -eq $hasValueProp.count) {
$handled = $true
Write-Warning -Message $e.message
}
else {
$handled = $true
Write-Warning -Message $e.value.message
}
}
catch {
$msg = "An error occurred: $($ex.Exception.Message)"
}
if (-not $handled) {
throw $ex
}
}
function _isVSTS {
param(
[parameter(Mandatory = $true)]
[string] $instance
)
return $instance -like "*.visualstudio.com*" -or $instance -like "https://dev.azure.com/*"
}
function _getVSTeamAPIVersion {
param(
[parameter(Mandatory = $true)]
[string] $instance,
[string] $Version
)
if ($Version) {
return $Version
}
else {
if (_isVSTS $instance) {
return 'VSTS'
}
else {
return 'TFS2017'
}
}
}
function _isOnWindows {
$os = Get-OperatingSystem
return $os -eq 'Windows'
}
function _addSubDomain {
param(
[string] $subDomain,
[string] $instance
)
# For VSTS Entitlements is under .vsaex
if ($subDomain -and $instance.ToLower().Contains('dev.azure.com')) {
$instance = $instance.ToLower().Replace('dev.azure.com', "$subDomain.dev.azure.com")
}
return $instance
}
function _appendQueryString {
param(
$name,
$value,
# When provided =0 will be outputed otherwise zeros will not be
# added. I had to add this for the userentitlements that is the only
# VSTS API I have found that requires Top and Skip to be passed in.
[Switch]$retainZero
)
if ($retainZero.IsPresent) {
if ($null -ne $value) {
return "&$name=$value"
}
}
else {
if ($value) {
return "&$name=$value"
}
}
}
function _getUserAgent {
[CmdletBinding()]
param()
$os = Get-OperatingSystem
$result = "Team Module/$([vsteam_lib.Versions]::ModuleVersion) ($os) PowerShell/$($PSVersionTable.PSVersion.ToString())"
Write-Verbose $result
return $result
}
function _useWindowsAuthenticationOnPremise {
return (_isOnWindows) -and (!$env:TEAM_PAT) -and -not ($(_getInstance) -like "*visualstudio.com") -and -not ($(_getInstance) -like "https://dev.azure.com/*")
}
function _useBearerToken {
return (!$env:TEAM_PAT) -and ($env:TEAM_TOKEN)
}
function _getWorkItemTypes {
param(
[Parameter(Mandatory = $true)]
[string] $ProjectName
)
if (-not $(_getInstance)) {
Write-Output @()
return
}
# Call the REST API
try {
$resp = _callAPI -ProjectName $ProjectName `
-area wit `
-resource workitemtypes `
-version $(_getApiVersion Core)
# This call returns JSON with "": which causes the ConvertFrom-Json to fail.
# To replace all the "": with "_end":
$resp = $resp.Replace('"":', '"_end":') | ConvertFrom-Json
if ($resp.count -gt 0) {
Write-Output ($resp.value).name
}
}
catch {
Write-Verbose $_
Write-Output @()
}
}
function _buildLevelDynamicParam {
param ()
# # Only add these options on Windows Machines
if (_isOnWindows) {
$ParameterName = 'Level'
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $false
$ParameterAttribute.HelpMessage = "On Windows machines allows you to store the default project at the process, user or machine level. Not available on other platforms."
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
# Generate and set the ValidateSet
if (_testAdministrator) {
$arrSet = "Process", "User", "Machine"
}
else {
$arrSet = "Process", "User"
}
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
}
}
function _buildProjectNameDynamicParam {
param(
[string] $ParameterName = 'ProjectName',
[string] $ParameterSetName,
[bool] $Mandatory = $true,
[string] $AliasName,
[int] $Position = 0
)
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $Mandatory
$ParameterAttribute.Position = $Position
if ($ParameterSetName) {
$ParameterAttribute.ParameterSetName = $ParameterSetName
}
$ParameterAttribute.ValueFromPipelineByPropertyName = $true
$ParameterAttribute.HelpMessage = "The name of the project. You can tab complete from the projects in your Team Services or TFS account when passed on the command line."
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
if ($AliasName) {
$AliasAttribute = New-Object System.Management.Automation.AliasAttribute(@($AliasName))
$AttributeCollection.Add($AliasAttribute)
}
# Generate and set the ValidateSet
$arrSet = [vsteam_lib.ProjectCache]::GetCurrent($false)
if ($arrSet) {
Write-Verbose "arrSet = $arrSet"
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
}
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
<#
Builds a dynamic parameter that can be used to tab complete the ProjectName
parameter of functions from a list of projects from the added TFS Account.
You must call Set-VSTeamAccount before trying to use any function that relies
on this dynamic parameter or you will get an error.
This can only be used in Advanced Fucntion with the [CmdletBinding()] attribute.
The function must also have a begin block that maps the value to a common variable
like this.
DynamicParam {
# Generate and set the ValidateSet
$arrSet = Get-VSTeamProjects | Select-Object -ExpandProperty Name
_buildProjectNameDynamicParam -arrSet $arrSet
}
process {
# Bind the parameter to a friendly variable
$ProjectName = $PSBoundParameters[$ParameterName]
}
#>
}
function _buildProcessNameDynamicParam {
param(
[string] $ParameterName = 'ProcessName',
[string] $ParameterSetName,
[bool] $Mandatory = $true,
[string] $AliasName,
[int] $Position = 0
)
# Create the dictionary
$RuntimeParameterDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $Mandatory
$ParameterAttribute.Position = $Position
if ($ParameterSetName) {
$ParameterAttribute.ParameterSetName = $ParameterSetName
}
$ParameterAttribute.ValueFromPipelineByPropertyName = $true
$ParameterAttribute.HelpMessage = "The name of the process. You can tab complete from the processes in your Team Services or TFS account when passed on the command line."
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
if ($AliasName) {
$AliasAttribute = New-Object System.Management.Automation.AliasAttribute(@($AliasName))
$AttributeCollection.Add($AliasAttribute)
}
# Generate and set the ValidateSet
$arrSet = [vsteam_lib.ProcessTemplateCache]::GetCurrent()
if ($arrSet) {
Write-Verbose "arrSet = $arrSet"
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
}
# Create and return the dynamic parameter
$RuntimeParameter = New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, [string], $AttributeCollection)
$RuntimeParameterDictionary.Add($ParameterName, $RuntimeParameter)
return $RuntimeParameterDictionary
<#
Builds a dynamic parameter that can be used to tab complete the ProjectName
parameter of functions from a list of projects from the added TFS Account.
You must call Set-VSTeamAccount before trying to use any function that relies
on this dynamic parameter or you will get an error.
This can only be used in Advanced Fucntion with the [CmdletBinding()] attribute.
The function must also have a begin block that maps the value to a common variable
like this.
DynamicParam {
# Generate and set the ValidateSet
$arrSet = Get-VSTeamProjects | Select-Object -ExpandProperty Name
_buildProjectNameDynamicParam -arrSet $arrSet
}
process {
# Bind the parameter to a friendly variable
$ProjectName = $PSBoundParameters[$ParameterName]
}
#>
}
function _buildDynamicParam {
param(
[string] $ParameterName = 'QueueName',
[array] $arrSet,
[bool] $Mandatory = $false,
[string] $ParameterSetName,
[int] $Position = -1,
[type] $ParameterType = [string],
[bool] $ValueFromPipelineByPropertyName = $true,
[string] $AliasName,
[string] $HelpMessage
)
# Create the collection of attributes
$AttributeCollection = New-Object System.Collections.ObjectModel.Collection[System.Attribute]
<#
.SYNOPSIS
Short description
.DESCRIPTION
Long description
.PARAMETER ParameterName
Parameter description
.PARAMETER ParameterSetName
Parameter description
.PARAMETER Mandatory
Parameter description
.PARAMETER AliasName
Parameter description
.PARAMETER Position
Parameter description
.EXAMPLE
An example
.NOTES
General notes
#>
# Create and set the parameters' attributes
$ParameterAttribute = New-Object System.Management.Automation.ParameterAttribute
$ParameterAttribute.Mandatory = $Mandatory
$ParameterAttribute.ValueFromPipelineByPropertyName = $ValueFromPipelineByPropertyName
if ($Position -ne -1) {
$ParameterAttribute.Position = $Position
}
if ($ParameterSetName) {
$ParameterAttribute.ParameterSetName = $ParameterSetName
}
if ($HelpMessage) {
$ParameterAttribute.HelpMessage = $HelpMessage
}
# Add the attributes to the attributes collection
$AttributeCollection.Add($ParameterAttribute)
if ($AliasName) {
$AliasAttribute = New-Object System.Management.Automation.AliasAttribute(@($AliasName))
$AttributeCollection.Add($AliasAttribute)
}
if ($arrSet) {
# Generate and set the ValidateSet
$ValidateSetAttribute = New-Object System.Management.Automation.ValidateSetAttribute($arrSet)
# Add the ValidateSet to the attributes collection
$AttributeCollection.Add($ValidateSetAttribute)
}
# Create and return the dynamic parameter
return New-Object System.Management.Automation.RuntimeDefinedParameter($ParameterName, $ParameterType, $AttributeCollection)
}
function _convertSecureStringTo_PlainText {
[CmdletBinding()]
param(
[parameter(ParameterSetName = 'Secure', Mandatory = $true, HelpMessage = 'Secure String')]
[securestring] $SecureString
)
# Convert the securestring to a normal string
# this was the one technique that worked on Mac, Linux and Windows
$credential = New-Object System.Management.Automation.PSCredential 'unknown', $SecureString
return $credential.GetNetworkCredential().Password
}
function _trackProjectProgress {
param(
[Parameter(Mandatory = $true)] $Resp,
[string] $Title,
[string] $Msg
)
$i = 0
$x = 1
$y = 10
$status = $resp.status
# Track status
while ($status -ne 'failed' -and $status -ne 'succeeded') {
$status = (_callAPI -Url $resp.url).status
# oscillate back a forth to show progress
$i += $x
Write-Progress -Activity $title -Status $msg -PercentComplete ($i / $y * 100)
if ($i -eq $y -or $i -eq 0) {
$x *= -1
}
}
}
$iTracking = 0
$xTracking = 1
$yTracking = 10
$statusTracking = $null
function _trackServiceEndpointProgress {
param(
[Parameter(Mandatory = $true)]
[string] $projectName,
[Parameter(Mandatory = $true)]
$resp,
[string] $title,
[string] $msg
)
$iTracking = 0
$xTracking = 1
$yTracking = 10
$isReady = $false
# Track status
while (-not $isReady) {
$statusTracking = _callAPI -ProjectName $projectName -Area 'distributedtask' -Resource 'serviceendpoints' -Id $resp.id `
-Version $(_getApiVersion ServiceEndpoints)
$isReady = $statusTracking.isReady;
if (-not $isReady) {
$state = $statusTracking.operationStatus.state
if ($state -eq "Failed") {
throw $statusTracking.operationStatus.statusMessage
}
}
# oscillate back a forth to show progress
$iTracking += $xTracking
Write-Progress -Activity $title -Status $msg -PercentComplete ($iTracking / $yTracking * 100)
if ($iTracking -eq $yTracking -or $iTracking -eq 0) {
$xTracking *= -1
}
}
}
function _getModuleVersion {
# Read the version from the psd1 file.
# $content = (Get-Content -Raw "./VSTeam.psd1" | Out-String)
$content = (Get-Content -Raw "$here\VSTeam.psd1" | Out-String)
$r = [regex]"ModuleVersion += +'([^']+)'"
$d = $r.Match($content)
return $d.Groups[1].Value
}
function _setEnvironmentVariables {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
param (
[string] $Level = "Process",
[string] $Pat,
[string] $Acct,
[string] $BearerToken,
[string] $Version
)
# You always have to set at the process level or they will Not
# be seen in your current session.
$env:TEAM_PAT = $Pat
$env:TEAM_ACCT = $Acct
$env:TEAM_VERSION = $Version
$env:TEAM_TOKEN = $BearerToken
[vsteam_lib.Versions]::Account = $Acct
# This is so it can be loaded by default in the next session
if ($Level -ne "Process") {
[System.Environment]::SetEnvironmentVariable("TEAM_PAT", $Pat, $Level)
[System.Environment]::SetEnvironmentVariable("TEAM_ACCT", $Acct, $Level)
[System.Environment]::SetEnvironmentVariable("TEAM_VERSION", $Version, $Level)
}
}
# If you remove an account the current default project needs to be cleared as well.
function _clearEnvironmentVariables {
[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSUseDeclaredVarsMoreThanAssignments", "")]
param (
[string] $Level = "Process"
)
$env:TEAM_PROJECT = $null
$env:TEAM_TIMEOUT = $null
[vsteam_lib.Versions]::DefaultProject = ''
[vsteam_lib.Versions]::DefaultTimeout = ''
$Global:PSDefaultParameterValues.Remove("*-vsteam*:projectName")
$Global:PSDefaultParameterValues.Remove("*-vsteam*:vsteamApiTimeout")
# This is so it can be loaded by default in the next session
if ($Level -ne "Process") {
[System.Environment]::SetEnvironmentVariable("TEAM_PROJECT", $null, $Level)
[System.Environment]::SetEnvironmentVariable("TEAM_TIMEOUT", $null, $Level)
}
_setEnvironmentVariables -Level $Level -Pat '' -Acct '' -UseBearerToken '' -Version ''
}
function _convertToHex() {
[cmdletbinding()]
param(
[parameter(Mandatory = $true)]
[string]$Value
)
$bytes = $Value | Format-Hex -Encoding Unicode
$hexString = ($bytes.Bytes | ForEach-Object ToString X2) -join ''
return $hexString.ToLowerInvariant();
}
function _getVSTeamIdFromDescriptor {
[cmdletbinding()]
param(
[parameter(Mandatory = $true)]
[string]$Descriptor
)
$identifier = $Descriptor.Split('.')[1]
# We need to Pad the string for FromBase64String to work reliably (AzD Descriptors are not padded)
$ModulusValue = ($identifier.length % 4)
Switch ($ModulusValue) {
'0' { $Padded = $identifier }
'1' { $Padded = $identifier.Substring(0, $identifier.Length - 1) }
'2' { $Padded = $identifier + ('=' * (4 - $ModulusValue)) }
'3' { $Padded = $identifier + ('=' * (4 - $ModulusValue)) }
}
return [System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($Padded))
}
function _getPermissionInheritanceInfo {
[cmdletbinding()]
[OutputType([System.Collections.Hashtable])]
param(
[parameter(Mandatory = $true)]