diff --git a/Build.md b/Build.md
new file mode 100644
index 0000000..904fde5
--- /dev/null
+++ b/Build.md
@@ -0,0 +1,64 @@
+# Building an Azure DevOps Web Extension
+
+To build an Azure DevOps web extension, follow these steps:
+
+1. **Prerequisites**
+ - Ensure you have Node.js and npm installed on your machine. You can download them from the official Node.js website: [Node.js](https://nodejs.org).
+
+2. **Create a new directory**
+ - Open a terminal or command prompt and navigate to the desired location where you want to create your extension project.
+ - Run the following command to create a new directory for your extension:
+ ```bash
+ mkdir my-extension
+ cd my-extension
+ ```
+
+3. **Initialize the project**
+ - Run the following command to initialize a new Node.js project:
+ ```bash
+ npm init -y
+ ```
+
+4. **Install the Azure DevOps Extension SDK**
+ - Run the following command to install the Azure DevOps Extension SDK:
+ ```bash
+ npm install azure-devops-extension-sdk --save
+ ```
+
+5. **Create your extension**
+ - Create the necessary files and folders for your extension, such as HTML, CSS, and JavaScript files.
+ - Refer to the [Azure DevOps Extension SDK documentation](https://docs.microsoft.com/azure/devops/extend/overview?view=azure-devops-extension-sdk-12) for more information on how to create and structure your extension.
+
+6. **Build and package your extension**
+ - Run the following command to build and package your extension:
+ ```bash
+ npm run build
+ ```
+
+7. **Publish your extension**
+ - Follow the instructions in the [Publish an Azure DevOps extension](https://docs.microsoft.com/azure/devops/extend/publish/overview?view=azure-devops-extension-sdk-12) documentation to publish your extension to the Azure DevOps Marketplace.
+
+That's it! You have now built and published your Azure DevOps web extension. For more detailed information and advanced topics, refer to the [Microsoft Learn documentation](https://docs.microsoft.com/learn/azure-devops/).
+
+# Package and Publish
+NOTE: before packaging, remember to increase your package version on the vss-extension.json file.
+
+8. **Package your extension**
+ - Run the following command to package your extension:
+ ```bash
+ tfx extension create --manifest-globs vss-extension.json
+ ```
+ - This command will create a VSIX package file for your extension.
+
+9. **Publish your extension**
+ - To publish your extension to the Azure DevOps Marketplace, you need to have an Azure DevOps organization and a publisher account.
+ - Run the following command to publish your extension:
+ ```bash
+ tfx extension publish --service-url https://dev.azure.com/{organization} --token {PAT}
+ ```
+ - Replace `{organization}` with your Azure DevOps organization name and `{PAT}` with a Personal Access Token (PAT) that has the necessary permissions to publish extensions.
+ - This command will publish your extension to the Azure DevOps Marketplace.
+
+ NOTE: alternatively, you can publish your extension using the GUI available at https://marketplace.visualstudio.com/manage/publishers/{organization} where organization is the name of your publisher company.
+
+That's it! You have now packaged and published your Azure DevOps web extension. Congratulations!
\ No newline at end of file
diff --git a/apim/v1/apim.ps1 b/apim/v1/apim.ps1
deleted file mode 100644
index 598a93b..0000000
--- a/apim/v1/apim.ps1
+++ /dev/null
@@ -1,162 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
- #getting inputs
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $product=Get-VstsInput -Name product1
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- #preparing endpoints
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json = '{
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+$($SwaggerLocation)+'",
- "path": "'+$($newapi)+'"
- }
- }'
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
-
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apim/v1/task.json b/apim/v1/task.json
deleted file mode 100644
index ef8d1bd..0000000
--- a/apim/v1/task.json
+++ /dev/null
@@ -1,209 +0,0 @@
-{
- "id": "fbb5ba7e-f837-4f46-b31e-f34c117fdd05",
- "name": "apim",
- "friendlyName": "API Management - Create or Update API",
- "description": "API Management - Create or update API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "7"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal"
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "false"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "False"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "Swagger Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": ""
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "CacheLookup",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apim.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apim/v2/apim.ps1 b/apim/v2/apim.ps1
deleted file mode 100644
index e594baf..0000000
--- a/apim/v2/apim.ps1
+++ /dev/null
@@ -1,228 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
- #getting inputs
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SwaggerPicker = Get-VstsInput -Name SwaggerPicker
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $swaggercode=Get-VstsInput -Name swaggercode
- $swaggerartifact=Get-VstsInput -Name swaggerartifact
- $product=Get-VstsInput -Name product1
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- $path = Get-VstsInput -Name pathapi
- $Authorization = Get-VstsInput -Name Authorization
- $oid = Get-VstsInput -Name oid
- $oauth = Get-VstsInput -Name oauth
- $AuthorizationBits='"authenticationSettings":null'
- switch($Authorization)
- {
- 'OAuth' {$AuthorizationBits='"authenticationSettings":{"oAuth2":{"authorizationServerId":"'+$oauth+'","scope":null}}'}
- 'OpenID' {$AuthorizationBits='"authenticationSettings":{"openid":{"openidProviderId":"'+$oid+'"}}'}
-
- }
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- #preparing endpoints
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json = ""
- switch($SwaggerPicker)
- {
- "Url" {
- $json = '{
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+$($SwaggerLocation)+'",
- "displayName": "'+$($newapi)+'",
- "path": "'+$($path)+'"
- }
- }'
- }
- "Artifact" {
- try {
- Assert-VstsPath -LiteralPath $swaggerartifact -PathType Leaf
- $swaggercode = Get-Content "$($swaggerartifact)"
- $json = '{
- "properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
- "displayName": "'+$($newapi)+'",
- "path": "'+$($path)+'"
- }
- }'
- } catch {
- Write-Error "Invalid file location $($swaggerartifact)"
- }
- }
- "Code" {
- $json = '{
- "properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
- "displayName": "'+$($newapi)+'",
- "path": "'+$($path)+'"
- }
- }'
- }
- default {Write-Error "Invalid swagger definition"}
- }
-
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- $json = '{
- "properties": { "id":"/apis/'+$($newapi)+'",
- "protocols":["https"],
- "name": "'+$($newapi)+'",
- "path": "'+$($path)+'",'+$AuthorizationBits+'
- }
- }'
- Write-Host "Updating with authorization information"
- Write-Host $json
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Patch -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
-
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apim/v2/icon.png b/apim/v2/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apim/v2/icon.png and /dev/null differ
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apim/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/module.json b/apim/v2/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apim/v2/ps_modules/VstsAzureHelpers_/tsconfig.json b/apim/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apim/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Minimatch.dll b/apim/v2/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apim/v2/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apim/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apim/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apim/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apim/v2/ps_modules/VstsTaskSdk/lib.json b/apim/v2/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apim/v2/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apim/v2/task.json b/apim/v2/task.json
deleted file mode 100644
index c255ff1..0000000
--- a/apim/v2/task.json
+++ /dev/null
@@ -1,309 +0,0 @@
-{
- "id": "fbb5ba7e-f837-4f46-b31e-f34c117fdd05",
- "name": "apim",
- "friendlyName": "API Management - Create or Update API",
- "description": "API Management - Create or update API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "2",
- "Minor": "3",
- "Patch": "3"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "Authorization",
- "type": "pickList",
- "label": "Authorization",
- "required": true,
- "helpMarkDown": "Enable Authorization for the developer portal",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "OAuth":"OAuth",
- "OpenID":"OpenID Connect"
- }
- },
- {
- "name": "oauth",
- "type": "pickList",
- "label": "Authorization server",
- "required": false,
- "helpMarkDown": "Authorization server to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OAuth"
- },
- {
- "name": "oid",
- "type": "pickList",
- "label": "OpenID Connect",
- "required": false,
- "helpMarkDown": "OpenID provider to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OpenID"
- },
- {
- "name": "SwaggerPicker",
- "type": "pickList",
- "label": "Swagger location",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Url",
- "options": {
- "Url": "Url",
- "Code":"Code",
- "Artifact":"Build Artifact"
- }
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "Swagger Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Url"
- },
- {
- "name": "swaggerartifact",
- "type": "string",
- "label": "Swagger Artifact",
- "required": true,
- "helpMarkDown": "Swagger Artifact. For instance $(System.DefaultWorkingDirectory)/",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Artifact"
- },
- {
- "name": "swaggercode",
- "type": "multiline",
- "label": "Swagger body",
- "required": true,
- "helpMarkDown": "Insert the full swagger definition",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Code"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oauth",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/authorizationServers?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oid",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/openidConnectProviders?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apim.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apim/v3/apim.ps1 b/apim/v3/apim.ps1
deleted file mode 100644
index 776eaa0..0000000
--- a/apim/v3/apim.ps1
+++ /dev/null
@@ -1,326 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
- #getting inputs
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- $DisplayName=Get-VstsInput -Name DisplayName
- if([string]::IsNullOrEmpty($DisplayName))
- {
- $DisplayName=$newapi
- }
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SwaggerPicker = Get-VstsInput -Name SwaggerPicker
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $swaggercode=Get-VstsInput -Name swaggercode
- $swaggerartifact=Get-VstsInput -Name swaggerartifact
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- $path = Get-VstsInput -Name pathapi
- $MicrosoftApiManagementAPIVersion = Get-VstsInput -Name MicrosoftApiManagementAPIVersion
- $Authorization = Get-VstsInput -Name Authorization
- $oid = Get-VstsInput -Name oid
- $oauth = Get-VstsInput -Name oauth
- $AuthorizationBits='"authenticationSettings":null'
- $OpenAPISpec=Get-VstsInput -Name OpenAPISpec
- $Format=Get-VstsInput -Name Format
- Add-Type -AssemblyName System.Web
- switch($Authorization)
- {
- 'OAuth' {$AuthorizationBits='"authenticationSettings":{"oAuth2":{"authorizationServerId":"'+$oauth+'","scope":null}}'}
- 'OpenID' {$AuthorizationBits='"authenticationSettings":{"openid":{"openidProviderId":"'+$oid+'"}}'}
-
- }
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- #preparing endpoints
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json = ""
- switch($SwaggerPicker)
- {
- "Url" {
- if($OpenAPISpec -eq "v2")
- {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+$($SwaggerLocation)+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "protocols":["https"]
- }
- }'
- }
- else {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
-"displayName": "'+$($DisplayName)+'",
- "contentFormat": "openapi-link",
- "contentValue": "'+$($SwaggerLocation)+'",
- "path": "'+$($path)+'",
- "protocols":["https"]
- }
- }'
- }
- }
- "Artifact" {
- try {
- Assert-VstsPath -LiteralPath $swaggerartifact -PathType Leaf
-
- $swaggercode = Get-Content "$($swaggerartifact)" -Raw
-
- if($OpenAPISpec -eq "v2")
- {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "protocols":["https"]
- }
- }'
- } else{
- $swaggercode=$swaggercode.Replace("`r`n","`n")
- $swaggercode =[System.Web.HttpUtility]::JavaScriptStringEncode($swaggercode)
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "'+$($contentFormat)+'",
- "contentValue": "'+$($swaggercode)+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "protocols":["https"]
- }
- }'
- }
-
-
- } catch {
- Write-Error "Invalid file location $($swaggerartifact)"
- }
- }
- "Code" {
- if($OpenAPISpec -eq "v2")
- {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'"
- }
- }'
- }
- else {
- $swaggercode=$swaggercode.Replace("`r`n","`n")
- $swaggercode =[System.Web.HttpUtility]::JavaScriptStringEncode($swaggercode)
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
-"displayName": "'+$($DisplayName)+'",
- "contentFormat": "'+$($contentFormat)+'",
- "contentValue": "'+$($swaggercode)+'",
- "path": "'+$($path)+'",
- "protocols":["https"]
- }
- }'
- }
-
- }
- default {Write-Error "Invalid swagger definition"}
- }
-
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- $json = '{
-"id": "/apis/'+$($newapi)+'",
-"name": "'+$($newapi)+'",
- "properties": {
-"displayName": "'+$($DisplayName)+'",
- "protocols":["https"],
- "path": "'+$($path)+'",'+$AuthorizationBits+'
- }
- }'
- Write-Host "Updating with authorization information"
- Write-Host $json
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Patch -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=$($MicrosoftApiManagementAPIVersion)"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apim/v3/icon.png b/apim/v3/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apim/v3/icon.png and /dev/null differ
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apim/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/module.json b/apim/v3/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apim/v3/ps_modules/VstsAzureHelpers_/tsconfig.json b/apim/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apim/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Minimatch.dll b/apim/v3/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apim/v3/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apim/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apim/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apim/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apim/v3/ps_modules/VstsTaskSdk/lib.json b/apim/v3/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apim/v3/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apim/v3/task.json b/apim/v3/task.json
deleted file mode 100644
index 1e9750d..0000000
--- a/apim/v3/task.json
+++ /dev/null
@@ -1,355 +0,0 @@
-{
- "id": "fbb5ba7e-f837-4f46-b31e-f34c117fdd05",
- "name": "apim",
- "friendlyName": "API Management - Create or Update API",
- "description": "API Management - Create or update API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "3",
- "Minor": "3",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "OpenAPISpec",
- "type": "pickList",
- "label": "OpenAPI Version",
- "required": true,
- "helpMarkDown": "Target Open API version.",
- "defaultValue": "v2",
- "options": {
- "v2": "v2",
- "v3":"v3"
- }
- },
- {
- "name": "Format",
- "type": "pickList",
- "label": "API definition format",
- "required": true,
- "helpMarkDown": "API definition format",
- "defaultValue": "json",
- "options": {
- "json": "json",
- "yaml":"yaml"
- },
- "visibleRule": "OpenAPISpec=v3"
- },
- {
- "name": "Authorization",
- "type": "pickList",
- "label": "Authorization",
- "required": true,
- "helpMarkDown": "Enable Authorization for the developer portal",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "OAuth":"OAuth",
- "OpenID":"OpenID Connect"
- }
- },
- {
- "name": "oauth",
- "type": "pickList",
- "label": "Authorization server",
- "required": false,
- "helpMarkDown": "Authorization server to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OAuth"
- },
- {
- "name": "oid",
- "type": "pickList",
- "label": "OpenID Connect",
- "required": false,
- "helpMarkDown": "OpenID provider to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OpenID"
- },
- {
- "name": "SwaggerPicker",
- "type": "pickList",
- "label": "Definition location",
- "required": true,
- "helpMarkDown": "Where is the API definition?",
- "defaultValue": "Url",
- "options": {
- "Url": "Url",
- "Code":"Code",
- "Artifact":"Build Artifact"
- }
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "Definition Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Url"
- },
- {
- "name": "swaggerartifact",
- "type": "string",
- "label": "Definition Artifact",
- "required": true,
- "helpMarkDown": "Definition Artifact. For instance $(System.DefaultWorkingDirectory)/",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Artifact"
- },
- {
- "name": "swaggercode",
- "type": "multiline",
- "label": "Definition body",
- "required": true,
- "helpMarkDown": "Insert the full API definition",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Code"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "DisplayName",
- "type": "string",
- "label": "API Display Name",
- "helpMarkDown": "Leave it blank to reuse the name"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "MicrosoftApiManagementAPIVersion",
- "type": "pickList",
- "label": "Microsoft API Version",
- "required": true,
- "helpMarkDown": "Which version of the Management API should be used?",
- "defaultValue": "2017-03-01",
- "options": {
- "2017-03-01": "2017-03-01",
- "2018-01-01":"2018-01-01"
- },
- "properties": {
- "EditableOptions": "True"
- }
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oauth",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/authorizationServers?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oid",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/openidConnectProviders?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apim.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apim/v4/apim.ps1 b/apim/v4/apim.ps1
deleted file mode 100644
index f43305d..0000000
--- a/apim/v4/apim.ps1
+++ /dev/null
@@ -1,333 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
- #getting inputs
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- $DisplayName=Get-VstsInput -Name DisplayName
- if([string]::IsNullOrEmpty($DisplayName))
- {
- $DisplayName=$newapi
- }
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SwaggerPicker = Get-VstsInput -Name SwaggerPicker
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $swaggercode=Get-VstsInput -Name swaggercode
- $swaggerartifact=Get-VstsInput -Name swaggerartifact
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- $path = Get-VstsInput -Name pathapi
- $MicrosoftApiManagementAPIVersion = Get-VstsInput -Name MicrosoftApiManagementAPIVersion
- $Authorization = Get-VstsInput -Name Authorization
- $oid = Get-VstsInput -Name oid
- $oauth = Get-VstsInput -Name oauth
- $AuthorizationBits='"authenticationSettings":null'
- $subscriptionRequired=Get-VstsInput -Name subscriptionRequired
- $OpenAPISpec=Get-VstsInput -Name OpenAPISpec
- $Format=Get-VstsInput -Name Format
- Add-Type -AssemblyName System.Web
- switch($Authorization)
- {
- 'OAuth' {$AuthorizationBits='"authenticationSettings":{"oAuth2":{"authorizationServerId":"'+$oauth+'","scope":null}}'}
- 'OpenID' {$AuthorizationBits='"authenticationSettings":{"openid":{"openidProviderId":"'+$oid+'"}}'}
-
- }
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- #preparing endpoints
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json = ""
- switch($SwaggerPicker)
- {
- "Url" {
- if($OpenAPISpec -eq "v2")
- {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+$($SwaggerLocation)+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "protocols":["https"],
- "subscriptionRequired":"'+$($subscriptionRequired)+'"
- }
- }'
- }
- else {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
-"displayName": "'+$($DisplayName)+'",
- "contentFormat": "openapi-link",
- "contentValue": "'+$($SwaggerLocation)+'",
- "path": "'+$($path)+'",
- "protocols":["https"],
- "subscriptionRequired":"'+$($subscriptionRequired)+'"
- }
- }'
- }
- }
- "Artifact" {
- try {
- Assert-VstsPath -LiteralPath $swaggerartifact -PathType Leaf
-
- $swaggercode = Get-Content "$($swaggerartifact)" -Raw
-
- if($OpenAPISpec -eq "v2")
- {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "protocols":["https"],
- "subscriptionRequired":"'+$($subscriptionRequired)+'"
- }
- }'
- } else{
- $swaggercode=$swaggercode.Replace("`r`n","`n")
- $swaggercode =[System.Web.HttpUtility]::JavaScriptStringEncode($swaggercode)
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "'+$($contentFormat)+'",
- "contentValue": "'+$($swaggercode)+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "protocols":["https"],
- "subscriptionRequired":"'+$($subscriptionRequired)+'"
- }
- }'
- }
-
-
- } catch {
- Write-Error "Invalid file location $($swaggerartifact)"
- }
- }
- "Code" {
- if($OpenAPISpec -eq "v2")
- {
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
- "displayName": "'+$($DisplayName)+'",
- "path": "'+$($path)+'",
- "subscriptionRequired":"'+$($subscriptionRequired)+'"
- }
- }'
- }
- else {
- $swaggercode=$swaggercode.Replace("`r`n","`n")
- $swaggercode =[System.Web.HttpUtility]::JavaScriptStringEncode($swaggercode)
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $json = '{
-"name": "'+$($newapi)+'",
-"id": "/apis/'+$($newapi)+'",
- "properties": {
-"displayName": "'+$($DisplayName)+'",
- "contentFormat": "'+$($contentFormat)+'",
- "contentValue": "'+$($swaggercode)+'",
- "path": "'+$($path)+'",
- "protocols":["https"],
- "subscriptionRequired":"'+$($subscriptionRequired)+'"
- }
- }'
- }
-
- }
- default {Write-Error "Invalid swagger definition"}
- }
-
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- $json = '{
-"id": "/apis/'+$($newapi)+'",
-"name": "'+$($newapi)+'",
- "properties": {
-"displayName": "'+$($DisplayName)+'",
- "protocols":["https"],
- "path": "'+$($path)+'",'+$AuthorizationBits+'
- }
- }'
- Write-Host "Updating with authorization information"
- Write-Host $json
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Patch -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=$($MicrosoftApiManagementAPIVersion)"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apim/v4/icon.png b/apim/v4/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apim/v4/icon.png and /dev/null differ
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apim/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/module.json b/apim/v4/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apim/v4/ps_modules/VstsAzureHelpers_/tsconfig.json b/apim/v4/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apim/v4/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Minimatch.dll b/apim/v4/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apim/v4/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apim/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apim/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apim/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apim/v4/ps_modules/VstsTaskSdk/lib.json b/apim/v4/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apim/v4/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apim/v4/task.json b/apim/v4/task.json
deleted file mode 100644
index 6ab2983..0000000
--- a/apim/v4/task.json
+++ /dev/null
@@ -1,362 +0,0 @@
-{
- "id": "fbb5ba7e-f837-4f46-b31e-f34c117fdd05",
- "name": "apim",
- "friendlyName": "API Management - Create or Update API",
- "description": "API Management - Create or update API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "4",
- "Minor": "0",
- "Patch": "0"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "OpenAPISpec",
- "type": "pickList",
- "label": "OpenAPI Version",
- "required": true,
- "helpMarkDown": "Target Open API version.",
- "defaultValue": "v2",
- "options": {
- "v2": "v2",
- "v3":"v3"
- }
- },
- {
- "name": "Format",
- "type": "pickList",
- "label": "API definition format",
- "required": true,
- "helpMarkDown": "API definition format",
- "defaultValue": "json",
- "options": {
- "json": "json",
- "yaml":"yaml"
- },
- "visibleRule": "OpenAPISpec=v3"
- },
- {
- "name": "Authorization",
- "type": "pickList",
- "label": "Authorization",
- "required": true,
- "helpMarkDown": "Enable Authorization for the developer portal",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "OAuth":"OAuth",
- "OpenID":"OpenID Connect"
- }
- },
- {
- "name": "oauth",
- "type": "pickList",
- "label": "Authorization server",
- "required": false,
- "helpMarkDown": "Authorization server to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OAuth"
- },
- {
- "name": "oid",
- "type": "pickList",
- "label": "OpenID Connect",
- "required": false,
- "helpMarkDown": "OpenID provider to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OpenID"
- },
- {
- "name": "SwaggerPicker",
- "type": "pickList",
- "label": "Definition location",
- "required": true,
- "helpMarkDown": "Where is the API definition?",
- "defaultValue": "Url",
- "options": {
- "Url": "Url",
- "Code":"Code",
- "Artifact":"Build Artifact"
- }
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "Definition Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Url"
- },
- {
- "name": "swaggerartifact",
- "type": "string",
- "label": "Definition Artifact",
- "required": true,
- "helpMarkDown": "Definition Artifact. For instance $(System.DefaultWorkingDirectory)/",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Artifact"
- },
- {
- "name": "swaggercode",
- "type": "multiline",
- "label": "Definition body",
- "required": true,
- "helpMarkDown": "Insert the full API definition",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Code"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "DisplayName",
- "type": "string",
- "label": "API Display Name",
- "helpMarkDown": "Leave it blank to reuse the name"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "subscriptionRequired",
- "type": "boolean",
- "label": "Subscription Required",
- "helpMarkDown": "Subscription key is required to access this API",
- "defaultValue":true
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "MicrosoftApiManagementAPIVersion",
- "type": "pickList",
- "label": "Microsoft API Version",
- "required": true,
- "helpMarkDown": "Which version of the Management API should be used?",
- "defaultValue": "2017-03-01",
- "options": {
- "2017-03-01": "2017-03-01",
- "2018-01-01":"2018-01-01"
- },
- "properties": {
- "EditableOptions": "True"
- }
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oauth",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/authorizationServers?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oid",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/openidConnectProviders?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apim.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apim/v5/icon.png b/apim/v5/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apim/v5/icon.png and /dev/null differ
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apim/v5/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/module.json b/apim/v5/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apim/v5/ps_modules/VstsAzureHelpers_/tsconfig.json b/apim/v5/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apim/v5/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Minimatch.dll b/apim/v5/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apim/v5/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apim/v5/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apim/v5/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apim/v5/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apim/v5/ps_modules/VstsTaskSdk/lib.json b/apim/v5/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apim/v5/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apim/v5/apim.ps1 b/apim/v6/apim.ps1
similarity index 94%
rename from apim/v5/apim.ps1
rename to apim/v6/apim.ps1
index d0c7b70..b583146 100644
--- a/apim/v5/apim.ps1
+++ b/apim/v6/apim.ps1
@@ -135,8 +135,8 @@ shared VNET
"name": "'+$($newapi)+'",
"id": "/apis/'+$($newapi)+'",
"properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+$($SwaggerLocation)+'",
+ "format": "swagger-link-json",
+ "value": "'+$($SwaggerLocation)+'",
"displayName": "'+$($DisplayName)+'",
"path": "'+$($path)+'",
"protocols":["https"],
@@ -150,8 +150,8 @@ shared VNET
"id": "/apis/'+$($newapi)+'",
"properties": {
"displayName": "'+$($DisplayName)+'",
- "contentFormat": "openapi-link",
- "contentValue": "'+$($SwaggerLocation)+'",
+ "format": "openapi-link",
+ "value": "'+$($SwaggerLocation)+'",
"path": "'+$($path)+'",
"protocols":["https"],
"subscriptionRequired":"'+$($subscriptionRequired)+'"
@@ -171,8 +171,8 @@ shared VNET
"name": "'+$($newapi)+'",
"id": "/apis/'+$($newapi)+'",
"properties": {
- "contentFormat": "swagger-json",
- "contentValue": "'+$($swaggercode).Replace('"','\"')+'",
+ "format": "swagger-json",
+ "value": "'+$($swaggercode).Replace('"','\"')+'",
"displayName": "'+$($DisplayName)+'",
"path": "'+$($path)+'",
"protocols":["https"],
@@ -192,8 +192,8 @@ shared VNET
"name": "'+$($newapi)+'",
"id": "/apis/'+$($newapi)+'",
"properties": {
- "contentFormat": "'+$($contentFormat)+'",
- "contentValue": "'+$($swaggercode)+'",
+ "format": "'+$($contentFormat)+'",
+ "value": "'+$($swaggercode)+'",
"displayName": "'+$($DisplayName)+'",
"path": "'+$($path)+'",
"protocols":["https"],
@@ -236,8 +236,8 @@ shared VNET
"id": "/apis/'+$($newapi)+'",
"properties": {
"displayName": "'+$($DisplayName)+'",
- "contentFormat": "'+$($contentFormat)+'",
- "contentValue": "'+$($swaggercode)+'",
+ "format": "'+$($contentFormat)+'",
+ "value": "'+$($swaggercode)+'",
"path": "'+$($path)+'",
"protocols":["https"],
"subscriptionRequired":"'+$($subscriptionRequired)+'"
@@ -323,8 +323,9 @@ shared VNET
{
$policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=$($MicrosoftApiManagementAPIVersion)"
$JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
+ `"properties`": {
+ `"format`": `"rawxml`",
+ `"value`":`""+$PolicyContent+"`"
}
}"
Write-Host "Linking policy to API USING $($policyapiurl)"
diff --git a/apim/v1/icon.png b/apim/v6/icon.png
similarity index 100%
rename from apim/v1/icon.png
rename to apim/v6/icon.png
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
rename to apim/v6/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/L0.ts
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/L0.ts
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apim/v6/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
rename to apim/v6/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apim/v6/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
rename to apim/v6/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/module.json b/apim/v6/ps_modules/VstsAzureHelpers_/module.json
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/module.json
rename to apim/v6/ps_modules/VstsAzureHelpers_/module.json
diff --git a/apim/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apim/v6/ps_modules/VstsAzureHelpers_/tsconfig.json
similarity index 100%
rename from apim/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
rename to apim/v6/ps_modules/VstsAzureHelpers_/tsconfig.json
diff --git a/apim/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/FindFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/FindFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/InputFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/InputFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apim/v6/ps_modules/VstsTaskSdk/Minimatch.dll
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Minimatch.dll
rename to apim/v6/ps_modules/VstsTaskSdk/Minimatch.dll
diff --git a/apim/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/OutFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/OutFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
rename to apim/v6/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
diff --git a/apim/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/ToolFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/ToolFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apim/v6/ps_modules/VstsTaskSdk/TraceFunctions.ps1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
rename to apim/v6/ps_modules/VstsTaskSdk/TraceFunctions.ps1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apim/v6/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
rename to apim/v6/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
diff --git a/apim/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apim/v6/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
rename to apim/v6/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apim/v6/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
rename to apim/v6/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
diff --git a/apim/v1/ps_modules/VstsTaskSdk/lib.json b/apim/v6/ps_modules/VstsTaskSdk/lib.json
similarity index 100%
rename from apim/v1/ps_modules/VstsTaskSdk/lib.json
rename to apim/v6/ps_modules/VstsTaskSdk/lib.json
diff --git a/apim/v5/task.json b/apim/v6/task.json
similarity index 98%
rename from apim/v5/task.json
rename to apim/v6/task.json
index 071d846..2aa4fd0 100644
--- a/apim/v5/task.json
+++ b/apim/v6/task.json
@@ -1,5 +1,5 @@
{
- "id": "fbb5ba7e-f837-4f46-b31e-f34c117fdd05",
+ "id": "6ecb50dd-caa7-46c5-b581-790a4762cd89",
"name": "apim",
"friendlyName": "API Management - Create or Update API",
"description": "API Management - Create or update API",
@@ -11,9 +11,9 @@
],
"demands": [],
"version": {
- "Major": "5",
+ "Major": "6",
"Minor": "0",
- "Patch": "2"
+ "Patch": "1"
},
"minimumAgentVersion": "1.95.0",
"instanceNameFormat": "API Management - Create/Update API $(message)",
@@ -315,10 +315,13 @@
"label": "Microsoft API Version",
"required": true,
"helpMarkDown": "Which version of the Management API should be used?",
- "defaultValue": "2017-03-01",
+ "defaultValue": "2022-08-01",
"options": {
"2017-03-01": "2017-03-01",
- "2018-01-01":"2018-01-01"
+ "2018-01-01":"2018-01-01",
+ "2021-08-01":"2021-08-01",
+ "2022-08-01":"2022-08-01",
+ "2023-05-01-preview":"2023-05-01-preview"
},
"properties": {
"EditableOptions": "True"
diff --git a/apimcreateorupdateproduct/v1/apimcreateorupdateproduct.ps1 b/apimcreateorupdateproduct/v1/apimcreateorupdateproduct.ps1
deleted file mode 100644
index 3ea9cef..0000000
--- a/apimcreateorupdateproduct/v1/apimcreateorupdateproduct.ps1
+++ /dev/null
@@ -1,153 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an APIM product.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $displayName=Get-VstsInput -Name DisplayName
- $product=Get-VstsInput -Name product
- $state=Get-VstsInput -Name state
- if($state -eq $true)
- {
- $state="published"
- }
- else
- {
- $state="notPUblished"
- }
- $subscriptionRequired=Get-VstsInput -Name subscriptionRequired
- $subscriptionRequired=$subscriptionRequired.ToString().ToLowerInvariant()
- $approvalRequired=Get-VstsInput -Name approvalRequired
- $approvalRequired=$approvalRequired.ToString().ToLowerInvariant()
- $subscriptionsLimit=Get-VstsInput -Name subscriptionsLimit
- if($subscriptionsLimit -eq $null -or $subscriptionsLimit -eq "")
- {
- $subscriptionsLimit='null'
- }
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "RateAndQuota")
- {
- $PolicyContent = Get-VstsInput -Name RateAndQuota
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- if($product.startswith("/subscriptions"))
- {
- $product=$product.substring($product.indexOf("/products")+10)
- }
- Write-Host "Product is $($product)"
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $producturl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/products/$($product)?api-version=2017-03-01"
- Write-Host $producturl
- if($displayName -eq $null -or $displayName -eq "")
- {
- $displayName=$product
- }
- Write-Host "DisplayName is $($displayName)"
-
- $json = '{
- "properties": {
- "displayName": "'+$displayName+'",
- "subscriptionRequired": '+$subscriptionRequired+',
- "approvalRequired": '+$approvalRequired+',
- "subscriptionsLimit":'+$subscriptionsLimit+',
- "state":"'+$state+'",
- }
- }'
-
- Write-Host $json
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $producturl -Headers $headers -Method Put -Body $json -ContentType "application/json"
- Write-Host ("##vso[task.setvariable variable=NewUpdatedProduct;]$product")
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/products/$($product)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/icon.png b/apimcreateorupdateproduct/v1/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimcreateorupdateproduct/v1/icon.png and /dev/null differ
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/module.json b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/lib.json b/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimcreateorupdateproduct/v1/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimcreateorupdateproduct/v1/task.json b/apimcreateorupdateproduct/v1/task.json
deleted file mode 100644
index ae14bed..0000000
--- a/apimcreateorupdateproduct/v1/task.json
+++ /dev/null
@@ -1,230 +0,0 @@
-{
- "id": "9a90d8a1-59bd-4e6d-a272-395ebca0781d",
- "name": "apimcreateorupdateproduct",
- "friendlyName": "API Management - Create or update product",
- "description": "API Management - Create or update product",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create or update product",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update Product $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal"
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "false"
- }
- },
- {
- "name": "product",
- "type": "pickList",
- "label": "product",
- "required": false,
- "helpMarkDown": "Add or update a product. Choose new name for a new product",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "DisplayName",
- "type": "pickList",
- "label": "Display Name",
- "required": true,
- "helpMarkDown": "Name appearing to subscribers",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "subscriptionRequired",
- "type": "boolean",
- "label": "Subscription Required",
- "helpMarkDown": "Should consumers subscribe to this product"
-
- },
- {
- "name": "approvalRequired",
- "type": "boolean",
- "label": "Approval Required",
- "helpMarkDown": "Should subscriber requests be approved"
-
- },
- {
- "name": "state",
- "type": "boolean",
- "required": false,
- "label": "Published",
- "helpMarkDown": "Is the product published or not"
- },
- {
- "name": "subscriptionsLimit",
- "type": "pickList",
- "label": "Subscription Limit",
- "properties": {
- "EditableOptions": "True"
- }
- },
-
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API. Make sure you type in valid XML and to adjust it to your needs.",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateAndQuota": "RateAndQuota",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Basic",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "JWT",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateAndQuota",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateAndQuota"
- },
- {
- "name": "RateByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t< calls='10000' bandwidth='40000' counter-key='@(context.Request.IpAddress)' renewal-period='3600'/>\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
-
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{id}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "DisplayName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/$(product)?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.properties.displayName"
- },
- {
- "target": "subscriptionsLimit",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/$(product)?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.properties.subscriptionsLimit"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimcreateorupdateproduct.ps1"
- }
- }
-}
diff --git a/apimcreateorupdateproduct/v2/apimcreateorupdateproduct.ps1 b/apimcreateorupdateproduct/v2/apimcreateorupdateproduct.ps1
deleted file mode 100644
index 238a25a..0000000
--- a/apimcreateorupdateproduct/v2/apimcreateorupdateproduct.ps1
+++ /dev/null
@@ -1,199 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an APIM product.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $displayName=Get-VstsInput -Name DisplayName
- $product=Get-VstsInput -Name product
- $state=Get-VstsInput -Name state
- $groups = $(Get-VstsInput -Name groups).Split([Environment]::NewLine)
-
- if($state -eq $true)
- {
- $state="published"
- }
- else
- {
- $state="notPUblished"
- }
- $subscriptionRequired=Get-VstsInput -Name subscriptionRequired
- $subscriptionRequired=$subscriptionRequired.ToString().ToLowerInvariant()
- $approvalRequired=Get-VstsInput -Name approvalRequired
- $approvalRequired=$approvalRequired.ToString().ToLowerInvariant()
- $subscriptionsLimit=Get-VstsInput -Name subscriptionsLimit
- if($subscriptionsLimit -eq $null -or $subscriptionsLimit -eq "")
- {
- $subscriptionsLimit='null'
- }
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "RateAndQuota")
- {
- $PolicyContent = Get-VstsInput -Name RateAndQuota
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- if($product.startswith("/subscriptions"))
- {
- $product=$product.substring($product.indexOf("/products")+10)
- }
- Write-Host "Product is $($product)"
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $producturl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/products/$($product)?api-version=2017-03-01"
- Write-Host $producturl
- if($displayName -eq $null -or $displayName -eq "")
- {
- $displayName=$product
- }
-
- Write-Host "DisplayName is $($displayName)"
- if ($subscriptionRequired -eq 'true')
- {
- $json = '{
- "properties": {
- "displayName": "'+$displayName+'",
- "subscriptionRequired": '+$subscriptionRequired+',
- "approvalRequired": '+$approvalRequired+',
- "subscriptionsLimit":'+$subscriptionsLimit+',
- "state":"'+$state+'",
- }
- }'
- }
- else
- {
- $json = '{
- "properties": {
- "displayName": "'+$displayName+'",
- "subscriptionRequired": '+$subscriptionRequired+',
- "state":"'+$state+'",
- }
- }'
- }
-
-
- Write-Host $json
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $producturl -Headers $headers -Method Put -Body $json -ContentType "application/json"
- Write-Host ("##vso[task.setvariable variable=NewUpdatedProduct;]$product")
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
-
- foreach ($group in $groups)
- {
- try
- {
- $groupapiurl = "$($baseurl)/products/$($product)/groups/$($group)?api-version=2018-01-01"
- Write-Host "Adding group to product $($groupapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $groupapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- foreach($existingProductGroup in $existingProductGroups.value)
- {
-
- if($null -eq ($g=$groups|where {$_ -eq $existingProductGroup.name}))
- {
- write-host "deleting product group $($existingProductGroup.name)"
- Invoke-Webrequest -UseBasicParsing -Uri "$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/products/$($product)/groups/$($existingProductGroup.name)?api-version=2017-03-01" -Method Delete -Headers $headers
- }
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/products/$($product)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/icon.png b/apimcreateorupdateproduct/v2/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimcreateorupdateproduct/v2/icon.png and /dev/null differ
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/module.json b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Minimatch.dll b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/lib.json b/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimcreateorupdateproduct/v2/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimcreateorupdateproduct/v2/task.json b/apimcreateorupdateproduct/v2/task.json
deleted file mode 100644
index 75b57d0..0000000
--- a/apimcreateorupdateproduct/v2/task.json
+++ /dev/null
@@ -1,253 +0,0 @@
-{
- "id": "9a90d8a1-59bd-4e6d-a272-395ebca0781d",
- "name": "apimcreateorupdateproduct",
- "friendlyName": "API Management - Create or update product",
- "description": "API Management - Create or update product",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create or update product",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "2",
- "Minor": "1",
- "Patch": "2"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update Product $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
-
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "product",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Add or update a product. Choose new name for a new product",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "DisplayName",
- "type": "pickList",
- "label": "Display Name",
- "required": true,
- "helpMarkDown": "Name appearing to subscribers",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "subscriptionRequired",
- "type": "boolean",
- "label": "Subscription Required",
- "helpMarkDown": "Should consumers subscribe to this product"
-
- },
- {
- "name": "subscriptionsLimit",
- "type": "pickList",
- "label": "Subscription Limit",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "subscriptionRequired = true"
- },
- {
- "name": "approvalRequired",
- "type": "boolean",
- "label": "Approval Required",
- "helpMarkDown": "Should subscriber requests be approved",
- "visibleRule": "subscriptionRequired = true"
- },
- {
- "name": "state",
- "type": "boolean",
- "required": false,
- "label": "Published",
- "helpMarkDown": "Is the product published or not"
- },
- {
- "name": "groups",
- "type": "multiline",
- "label": "Groups",
- "required": true,
- "helpMarkDown": "Groups to add. One group per line."
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API. Make sure you type in valid XML and to adjust it to your needs.",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "Basic": "Basic",
- "Custom": "Custom",
- "JWT": "JWT",
- "IP": "IP",
- "RateAndQuota": "RateAndQuota",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateAndQuota",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateAndQuota"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t< calls='10000' bandwidth='40000' counter-key='@(context.Request.IpAddress)' renewal-period='3600'/>\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
-
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{id}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "DisplayName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/$(product)?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.properties.displayName"
- },
- {
- "target": "subscriptionsLimit",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/$(product)?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.properties.subscriptionsLimit"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimcreateorupdateproduct.ps1"
- }
- }
-}
diff --git a/apimcreateorupdateproduct/v3/apimcreateorupdateproduct.ps1 b/apimcreateorupdateproduct/v3/apimcreateorupdateproduct.ps1
deleted file mode 100644
index a18a9a6..0000000
--- a/apimcreateorupdateproduct/v3/apimcreateorupdateproduct.ps1
+++ /dev/null
@@ -1,221 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an APIM product.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $displayName=Get-VstsInput -Name DisplayName
- $product=Get-VstsInput -Name product
- $state=Get-VstsInput -Name state
- $groups = $(Get-VstsInput -Name groups).Split([Environment]::NewLine)
-
- if($state -eq $true)
- {
- $state="published"
- }
- else
- {
- $state="notPUblished"
- }
- $subscriptionRequired=Get-VstsInput -Name subscriptionRequired
- $subscriptionRequired=$subscriptionRequired.ToString().ToLowerInvariant()
- $approvalRequired=Get-VstsInput -Name approvalRequired
- $approvalRequired=$approvalRequired.ToString().ToLowerInvariant()
- $subscriptionsLimit=Get-VstsInput -Name subscriptionsLimit
- if($subscriptionsLimit -eq $null -or $subscriptionsLimit -eq "")
- {
- $subscriptionsLimit='null'
- }
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "RateAndQuota")
- {
- $PolicyContent = Get-VstsInput -Name RateAndQuota
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- if($product.startswith("/subscriptions"))
- {
- $product=$product.substring($product.indexOf("/products")+10)
- }
- Write-Host "Product is $($product)"
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $producturl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/products/$($product)?api-version=2017-03-01"
- Write-Host $producturl
- if($displayName -eq $null -or $displayName -eq "")
- {
- $displayName=$product
- }
-
- Write-Host "DisplayName is $($displayName)"
- if ($subscriptionRequired -eq 'true')
- {
- $json = '{
- "properties": {
- "displayName": "'+$displayName+'",
- "subscriptionRequired": '+$subscriptionRequired+',
- "approvalRequired": '+$approvalRequired+',
- "subscriptionsLimit":'+$subscriptionsLimit+',
- "state":"'+$state+'",
- }
- }'
- }
- else
- {
- $json = '{
- "properties": {
- "displayName": "'+$displayName+'",
- "subscriptionRequired": '+$subscriptionRequired+',
- "state":"'+$state+'",
- }
- }'
- }
-
-
- Write-Host $json
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $producturl -Headers $headers -Method Put -Body $json -ContentType "application/json"
- Write-Host ("##vso[task.setvariable variable=NewUpdatedProduct;]$product")
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
- #checking whether the provided groups exist or not
- $odataFilter="("
- foreach($group in $groups)
- {
- $odataFilter+="name%20eq%20'"+$group+"'%20or%20"
- }
- $odataFilter=$odataFilter.Substring(0,$odataFilter.Length-8)
- $odataFilter+=")"
- $existingGroupsUri="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/groups?api-version=2017-03-01&"+'$filter='+"$($odataFilter)"
- $existingProductGroupsUri="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/products/$($product)/groups?api-version=2018-01-01"
- $existingProductGroups=Invoke-WebRequest -UseBasicParsing -Uri $existingProductGroupsUri -Headers $headers|ConvertFrom-Json
- Write-Host "getting existing groups $($existingGroupsUri)"
- $existingGroups=Invoke-WebRequest -UseBasicParsing -Uri $existingGroupsUri -Headers $headers|ConvertFrom-Json
-
- foreach ($group in $groups)
- {
- try
- {
- if($null -eq ($g=$existingGroups.value|where {$_.name -eq $group}))
- {
- write-host "creating group $($group)"
- $groupBody="{'properties':{'displayName':'$($group)'}}"
- Invoke-WebRequest -UseBasicParsing -Uri "$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/groups/$($group)?api-version=2017-03-01" -Method Put -ContentType application/json -Body $groupBody -Headers $headers
- }
- $groupapiurl = "$($baseurl)/products/$($product)/groups/$($group)?api-version=2018-01-01"
- Write-Host "Adding group to product $($groupapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $groupapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- foreach($existingProductGroup in $existingProductGroups.value)
- {
-
- if($null -eq ($g=$groups|where {$_ -eq $existingProductGroup.name}))
- {
- write-host "deleting product group $($existingProductGroup.name)"
- Invoke-Webrequest -UseBasicParsing -Uri "$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)/products/$($product)/groups/$($existingProductGroup.name)?api-version=2017-03-01" -Method Delete -Headers $headers
- }
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/products/$($product)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/icon.png b/apimcreateorupdateproduct/v3/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimcreateorupdateproduct/v3/icon.png and /dev/null differ
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/module.json b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Minimatch.dll b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/lib.json b/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimcreateorupdateproduct/v3/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimcreateorupdateproduct/v3/task.json b/apimcreateorupdateproduct/v3/task.json
deleted file mode 100644
index baaa33e..0000000
--- a/apimcreateorupdateproduct/v3/task.json
+++ /dev/null
@@ -1,253 +0,0 @@
-{
- "id": "9a90d8a1-59bd-4e6d-a272-395ebca0781d",
- "name": "apimcreateorupdateproduct",
- "friendlyName": "API Management - Create or update product",
- "description": "API Management - Create or update product",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create or update product",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "3",
- "Minor": "1",
- "Patch": "2"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update Product $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
-
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "product",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Add or update a product. Choose new name for a new product",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "DisplayName",
- "type": "pickList",
- "label": "Display Name",
- "required": true,
- "helpMarkDown": "Name appearing to subscribers",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "subscriptionRequired",
- "type": "boolean",
- "label": "Subscription Required",
- "helpMarkDown": "Should consumers subscribe to this product"
-
- },
- {
- "name": "subscriptionsLimit",
- "type": "pickList",
- "label": "Subscription Limit",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "subscriptionRequired = true"
- },
- {
- "name": "approvalRequired",
- "type": "boolean",
- "label": "Approval Required",
- "helpMarkDown": "Should subscriber requests be approved",
- "visibleRule": "subscriptionRequired = true"
- },
- {
- "name": "state",
- "type": "boolean",
- "required": false,
- "label": "Published",
- "helpMarkDown": "Is the product published or not"
- },
- {
- "name": "groups",
- "type": "multiline",
- "label": "Groups",
- "required": true,
- "helpMarkDown": "Groups to add. One group per line."
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API. Make sure you type in valid XML and to adjust it to your needs.",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "Basic": "Basic",
- "Custom": "Custom",
- "JWT": "JWT",
- "IP": "IP",
- "RateAndQuota": "RateAndQuota",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateAndQuota",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateAndQuota"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t< calls='10000' bandwidth='40000' counter-key='@(context.Request.IpAddress)' renewal-period='3600'/>\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
-
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{id}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "DisplayName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/$(product)?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.properties.displayName"
- },
- {
- "target": "subscriptionsLimit",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/$(product)?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.properties.subscriptionsLimit"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimcreateorupdateproduct.ps1"
- }
- }
-}
diff --git a/apimcreateorupdateproduct/v4/task.json b/apimcreateorupdateproduct/v4/task.json
index b02acba..ca4389b 100644
--- a/apimcreateorupdateproduct/v4/task.json
+++ b/apimcreateorupdateproduct/v4/task.json
@@ -1,5 +1,5 @@
{
- "id": "9a90d8a1-59bd-4e6d-a272-395ebca0781d",
+ "id": "1b7dc7f5-5c2e-438c-93f5-ff3e59b31f4f",
"name": "apimcreateorupdateproduct",
"friendlyName": "API Management - Create or update product",
"description": "API Management - Create or update product",
diff --git a/apimfunction/v1/apimfunction.ps1 b/apimfunction/v1/apimfunction.ps1
deleted file mode 100644
index 2e418d6..0000000
--- a/apimfunction/v1/apimfunction.ps1
+++ /dev/null
@@ -1,242 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an API against an Azure Function set. It will automatically enable Swagger for the functions and create an operation-level policy
-for each and every function to inject the function's code as query string parameter while calling the API.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi -ne $null -and $newapi.indexOf("/apis/")-ne -1)
- {
- $newapi=$newapi.Substring($newapi.indexOf("/apis")+6)
- }
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name APIResourceGroupName
- $functiongroup=Get-VstsInput -Name ResourceGroupName
- $functionsite=Get-VstsInput -Name HostingWebSite
- $product=Get-VstsInput -Name product1
-
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
-
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $functionbaseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($functiongroup)/providers/Microsoft.Web/sites/$($functionsite)"
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- $bodyadmin="resource=https%3A%2F%2Fmanagement.core.windows.net%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- $coremgt=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $bodyadmin| ConvertFrom-Json
-
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $adminscmheaders = @{
- Authorization = "Bearer $($coremgt.access_token)"
- }
- $adminresp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions/admin/token?api-version=2016-08-01" -Headers $headers
- $admintoken=$adminresp.Content|ConvertFrom-Json
- $adminheaders = @{
- Authorization = "Bearer $($admintoken)"
- }
- $json='{"swagger":{"enabled":true}}'
- Write-Host "Enabling Swagger for the target function set"
- Invoke-WebRequest -Body $json -UseBasicParsing "https://$($functionsite).scm.azurewebsites.net/api/functions/config" -Headers $adminscmheaders -Method Put -ContentType "application/json"
- #generating swagger key
- Write-Host "generating swagger key"
- $key=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey" -Method Post -Headers $adminheaders
- $keyjson=$key.Content|ConvertFrom-Json
- #noticed that calling the swagger definition too fast after getting a new key causes a 500 exception
- Start-Sleep -Seconds 2
- #non default swagger
- Write-Host "downloading swagger definition https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"
-
- $json = '{
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+"https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"+'",
- "path": "'+$($newapi)+'"
- }
- }'
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
-
- if($product -ne $null -and $product -ne "")
- {
- if($product.indexOf("/products/") -ne -1)
- {
- $product=$product.Substring($product.indexOf("/products/")+10)
- }
-
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
- Write-Host "iterating through operations $($baseurl)/apis/$($newapi)/operations?api-version=2017-03-01"
- $operationresponse=Invoke-WebRequest -UseBasicParsing "$($baseurl)/apis/$($newapi)/operations?api-version=2017-03-01" -Headers $headers
- $operations = $operationresponse.Content|ConvertFrom-Json
- $ops = @{}
- $operations.value|%{
- $ops.Add($_.properties.displayName,$_.name)
- }
- Write-Host "iterating through fucntions $($functionbaseurl)/functions?api-version=2016-08-01"
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions?api-version=2016-08-01" -Headers $headers
- $functions = $resp.Content|ConvertFrom-Json
- $headers.Add("If-Match","*")
- $functions.value|% {
- $fname=$_.name.Substring($_.name.IndexOf("/")+1)
- Write-Host "Getting function keys https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys"
- $keys=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys" -Headers $adminheaders
- $keys=$keys.Content|ConvertFrom-Json
- $thekey=$keys.keys[0].value
- $ops.Keys|%{
- if($_.ToString().indexOf("$fname/") -ne -1)
- {
- $targetfname=$ops[$_.ToString()]
- $json = "
-
- "+$thekey+"
-
-
-
-
-
-
-
-
-
-
-
-"
- Write-Host "setting operation policy $($baseurl)/apis/$($newapi)/operations/$($targetfname)/policy?api-version=2017-03-01"
- Invoke-WebRequest -Headers $headers -UseBasicParsing -Uri "$($baseurl)/apis/$($newapi)/operations/$($targetfname)/policy?api-version=2017-03-01" -Method Put -Body $json -ContentType "application/vnd.ms-azure-apim.policy.raw+xml"
- }
- }
-
-}
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimfunction/v1/icon.png b/apimfunction/v1/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimfunction/v1/icon.png and /dev/null differ
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimfunction/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/module.json b/apimfunction/v1/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimfunction/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimfunction/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apimfunction/v1/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimfunction/v1/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimfunction/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimfunction/v1/ps_modules/VstsTaskSdk/lib.json b/apimfunction/v1/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimfunction/v1/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimfunction/v1/task.json b/apimfunction/v1/task.json
deleted file mode 100644
index eff16ff..0000000
--- a/apimfunction/v1/task.json
+++ /dev/null
@@ -1,235 +0,0 @@
-{
- "id": "cad4b382-7e58-4e06-917a-d301ab1d52d9",
- "name": "apimfunction",
- "friendlyName": "API Management - Create or Update API on Azure Functions",
- "description": "API Management - Create or Update API on Azure Functions",
- "author": "Stephane Eyskens",
- "helpMarkDown": "Create or Update API on Azure Functions",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API on Function $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "APIResourceGroupName",
- "label": "API Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "false"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "API Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "False"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "CacheLookup",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "ResourceGroupName",
- "label": "Functions Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the Azure Functions"
- },
- {
- "name": "HostingWebSite",
- "type": "pickList",
- "label": "Functions Site",
- "required": true,
- "helpMarkDown": "Web site where your functions are deployed",
- "properties": {
- "EditableOptions": "true"
- }
- }
-
- ],
-
- "dataSourceBindings": [
- {
- "target": "APIResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(APIResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "HostingWebSite",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.Web/sites?api-version=2016-08-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{{{name}}}"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimfunction.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v2/apimfunction.ps1 b/apimfunction/v2/apimfunction.ps1
deleted file mode 100644
index ffb7f28..0000000
--- a/apimfunction/v2/apimfunction.ps1
+++ /dev/null
@@ -1,246 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an API against an Azure Function set. It will automatically enable Swagger for the functions and create an operation-level policy
-for each and every function to inject the function's code as query string parameter while calling the API.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi -ne $null -and $newapi.indexOf("/apis/")-ne -1)
- {
- $newapi=$newapi.Substring($newapi.indexOf("/apis")+6)
- }
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name APIResourceGroupName
- $functiongroup=Get-VstsInput -Name ResourceGroupName
- $functionsite=Get-VstsInput -Name HostingWebSite
- $product=Get-VstsInput -Name product1
-
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $path = Get-VstsInput -Name pathapi
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $functionbaseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($functiongroup)/providers/Microsoft.Web/sites/$($functionsite)"
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- $bodyadmin="resource=https%3A%2F%2Fmanagement.core.windows.net%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- $coremgt=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $bodyadmin| ConvertFrom-Json
-
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $adminscmheaders = @{
- Authorization = "Bearer $($coremgt.access_token)"
- }
- $adminresp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions/admin/token?api-version=2016-08-01" -Headers $headers
- $admintoken=$adminresp.Content|ConvertFrom-Json
- $adminheaders = @{
- Authorization = "Bearer $($admintoken)"
- }
- $json='{"swagger":{"enabled":true}}'
- Write-Host "Enabling Swagger for the target function set"
- Invoke-WebRequest -Body $json -UseBasicParsing "https://$($functionsite).scm.azurewebsites.net/api/functions/config" -Headers $adminscmheaders -Method Put -ContentType "application/json"
- #generating swagger key
- Write-Host "generating swagger key"
- $key=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey" -Method Post -Headers $adminheaders
- $keyjson=$key.Content|ConvertFrom-Json
- #noticed that calling the swagger definition too fast after getting a new key causes a 500 exception
- Start-Sleep -Seconds 2
- #non default swagger
- Write-Host "downloading swagger definition https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"
-
- $json = '{
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+"https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"+'",
- "path": "'+$($path)+'"
- }
- }'
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
-
- if($product -ne $null -and $product -ne "")
- {
- if($product.indexOf("/products/") -ne -1)
- {
- $product=$product.Substring($product.indexOf("/products/")+10)
- }
-
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
- Write-Host "iterating through operations $($baseurl)/apis/$($newapi)/operations?api-version=2017-03-01"
- $operationresponse=Invoke-WebRequest -UseBasicParsing "$($baseurl)/apis/$($newapi)/operations?api-version=2017-03-01" -Headers $headers
- $operations = $operationresponse.Content|ConvertFrom-Json
- $ops = @{}
- $operations.value|%{
- $ops.Add($_.properties.displayName,$_.name)
- }
- Write-Host "iterating through fucntions $($functionbaseurl)/functions?api-version=2016-08-01"
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions?api-version=2016-08-01" -Headers $headers
- $functions = $resp.Content|ConvertFrom-Json
- $headers.Add("If-Match","*")
- $functions.value|% {
- $fname=$_.name.Substring($_.name.IndexOf("/")+1)
- Write-Host "Getting function keys https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys"
- $keys=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys" -Headers $adminheaders
- $keys=$keys.Content|ConvertFrom-Json
- $thekey=$keys.keys[0].value
- $ops.Keys|%{
- if($_.ToString().indexOf("$fname/") -ne -1)
- {
- $targetfname=$ops[$_.ToString()]
- $json = "
-
- "+$thekey+"
-
-
-
-
-
-
-
-
-
-
-
-"
- Write-Host "setting operation policy $($baseurl)/apis/$($newapi)/operations/$($targetfname)/policy?api-version=2017-03-01"
- Invoke-WebRequest -Headers $headers -UseBasicParsing -Uri "$($baseurl)/apis/$($newapi)/operations/$($targetfname)/policy?api-version=2017-03-01" -Method Put -Body $json -ContentType "application/vnd.ms-azure-apim.policy.raw+xml"
- }
- }
-
-}
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimfunction/v2/icon.png b/apimfunction/v2/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimfunction/v2/icon.png and /dev/null differ
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimfunction/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/module.json b/apimfunction/v2/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimfunction/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimfunction/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Minimatch.dll b/apimfunction/v2/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimfunction/v2/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimfunction/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimfunction/v2/ps_modules/VstsTaskSdk/lib.json b/apimfunction/v2/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimfunction/v2/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimfunction/v2/task.json b/apimfunction/v2/task.json
deleted file mode 100644
index 6e250cb..0000000
--- a/apimfunction/v2/task.json
+++ /dev/null
@@ -1,257 +0,0 @@
-{
- "id": "cad4b382-7e58-4e06-917a-d301ab1d52d9",
- "name": "apimfunction",
- "friendlyName": "API Management - Create or Update API on Azure Functions (v1)",
- "description": "API Management - Create or Update API on Azure Functions (v1)",
- "author": "Stephane Eyskens",
- "helpMarkDown": "Create or Update API on Azure Functions",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "2",
- "Minor": "0",
- "Patch": "6"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API on Function(v1) $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "APIResourceGroupName",
- "label": "API Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "API Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "ResourceGroupName",
- "label": "Functions Resource Group",
- "type": "pickList",
- "required": true,
- "properties": {
- "EditableOptions": "True"
- },
- "helpMarkDown": "Select resource group which contains the Azure Functions"
- },
- {
- "name": "HostingWebSite",
- "type": "pickList",
- "label": "Functions Site",
- "required": true,
- "helpMarkDown": "Web site where your functions are deployed",
- "properties": {
- "EditableOptions": "True"
- }
- }
-
- ],
-
- "dataSourceBindings": [
- {
- "target": "APIResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(APIResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "HostingWebSite",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.Web/sites?api-version=2016-08-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{{{name}}}"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimfunction.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v3/apimfunction.ps1 b/apimfunction/v3/apimfunction.ps1
deleted file mode 100644
index 868c875..0000000
--- a/apimfunction/v3/apimfunction.ps1
+++ /dev/null
@@ -1,256 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an API against an Azure Function set. It will automatically enable Swagger for the functions and create an operation-level policy
-for each and every function to inject the function's code as query string parameter while calling the API.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi -ne $null -and $newapi.indexOf("/apis/")-ne -1)
- {
- $newapi=$newapi.Substring($newapi.indexOf("/apis")+6)
- }
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name APIResourceGroupName
- $functiongroup=Get-VstsInput -Name ResourceGroupName
- $functionsite=Get-VstsInput -Name HostingWebSite
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $path = Get-VstsInput -Name pathapi
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $functionbaseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($functiongroup)/providers/Microsoft.Web/sites/$($functionsite)"
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- $bodyadmin="resource=https%3A%2F%2Fmanagement.core.windows.net%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- $coremgt=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $bodyadmin| ConvertFrom-Json
-
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $adminscmheaders = @{
- Authorization = "Bearer $($coremgt.access_token)"
- }
- $adminresp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions/admin/token?api-version=2016-08-01" -Headers $headers
- $admintoken=$adminresp.Content|ConvertFrom-Json
- $adminheaders = @{
- Authorization = "Bearer $($admintoken)"
- }
- $json='{"swagger":{"enabled":true}}'
- Write-Host "Enabling Swagger for the target function set"
- Invoke-WebRequest -Body $json -UseBasicParsing "https://$($functionsite).scm.azurewebsites.net/api/functions/config" -Headers $adminscmheaders -Method Put -ContentType "application/json"
- #generating swagger key
- Write-Host "generating swagger key"
- $key=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey" -Method Post -Headers $adminheaders
- $keyjson=$key.Content|ConvertFrom-Json
- #noticed that calling the swagger definition too fast after getting a new key causes a 500 exception
- Start-Sleep -Seconds 2
- #non default swagger
- Write-Host "downloading swagger definition https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"
-
- $json = '{
- "properties": {
- "contentFormat": "swagger-link-json",
- "contentValue": "'+"https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"+'",
- "path": "'+$($path)+'"
- }
- }'
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- Write-Host "Creating or updating API $($targeturl)"
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- if($product.indexOf("/products/") -ne -1)
- {
- $product=$product.Substring($product.indexOf("/products/")+10)
- }
-
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
- Write-Host "iterating through operations $($baseurl)/apis/$($newapi)/operations?api-version=2017-03-01"
- $operationresponse=Invoke-WebRequest -UseBasicParsing "$($baseurl)/apis/$($newapi)/operations?api-version=2017-03-01" -Headers $headers
- $operations = $operationresponse.Content|ConvertFrom-Json
- $ops = @{}
- $operations.value|%{
- $ops.Add($_.properties.displayName,$_.name)
- }
- Write-Host "iterating through fucntions $($functionbaseurl)/functions?api-version=2016-08-01"
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions?api-version=2016-08-01" -Headers $headers
- $functions = $resp.Content|ConvertFrom-Json
- $headers.Add("If-Match","*")
- $functions.value|% {
- $fname=$_.name.Substring($_.name.IndexOf("/")+1)
- Write-Host "Getting function keys https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys"
- $keys=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys" -Headers $adminheaders
- $keys=$keys.Content|ConvertFrom-Json
- $thekey=$keys.keys[0].value
- $ops.Keys|%{
- if($_.ToString().indexOf("$fname/") -ne -1)
- {
- $targetfname=$ops[$_.ToString()]
- $json = "
-
- "+$thekey+"
-
-
-
-
-
-
-
-
-
-
-
-"
- Write-Host "setting operation policy $($baseurl)/apis/$($newapi)/operations/$($targetfname)/policy?api-version=2017-03-01"
- Invoke-WebRequest -Headers $headers -UseBasicParsing -Uri "$($baseurl)/apis/$($newapi)/operations/$($targetfname)/policy?api-version=2017-03-01" -Method Put -Body $json -ContentType "application/vnd.ms-azure-apim.policy.raw+xml"
- }
- }
-
-}
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimfunction/v3/icon.png b/apimfunction/v3/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimfunction/v3/icon.png and /dev/null differ
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimfunction/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/module.json b/apimfunction/v3/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimfunction/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimfunction/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Minimatch.dll b/apimfunction/v3/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimfunction/v3/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimfunction/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimfunction/v3/ps_modules/VstsTaskSdk/lib.json b/apimfunction/v3/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimfunction/v3/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimfunction/v3/task.json b/apimfunction/v3/task.json
deleted file mode 100644
index ec2a7e1..0000000
--- a/apimfunction/v3/task.json
+++ /dev/null
@@ -1,257 +0,0 @@
-{
- "id": "cad4b382-7e58-4e06-917a-d301ab1d52d9",
- "name": "apimfunction",
- "friendlyName": "API Management - Create or Update API on Azure Functions (v1)",
- "description": "API Management - Create or Update API on Azure Functions (v1)",
- "author": "Stephane Eyskens",
- "helpMarkDown": "Create or Update API on Azure Functions",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "3",
- "Minor": "0",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API on Function(v1) $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "APIResourceGroupName",
- "label": "API Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
-
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "ResourceGroupName",
- "label": "Functions Resource Group",
- "type": "pickList",
- "required": true,
- "properties": {
- "EditableOptions": "True"
- },
- "helpMarkDown": "Select resource group which contains the Azure Functions"
- },
- {
- "name": "HostingWebSite",
- "type": "pickList",
- "label": "Functions Site",
- "required": true,
- "helpMarkDown": "Web site where your functions are deployed",
- "properties": {
- "EditableOptions": "True"
- }
- }
-
- ],
-
- "dataSourceBindings": [
- {
- "target": "APIResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(APIResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "HostingWebSite",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.Web/sites?api-version=2016-08-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{{{name}}}"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimfunction.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimfunction/v4/task.json b/apimfunction/v4/task.json
index d29b749..eff8248 100644
--- a/apimfunction/v4/task.json
+++ b/apimfunction/v4/task.json
@@ -1,5 +1,5 @@
{
- "id": "cad4b382-7e58-4e06-917a-d301ab1d52d9",
+ "id": "f9f9b407-62d1-42f7-93d7-044b00706470",
"name": "apimfunction",
"friendlyName": "API Management - Create or Update API on Azure Functions (v1)",
"description": "API Management - Create or Update API on Azure Functions (v1)",
diff --git a/apimfunctionversioned/v1/apimfunctionversioned.ps1 b/apimfunctionversioned/v1/apimfunctionversioned.ps1
deleted file mode 100644
index f4f6c8a..0000000
--- a/apimfunctionversioned/v1/apimfunctionversioned.ps1
+++ /dev/null
@@ -1,344 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against an Azure Function set.
-Prerequisite to using this task: VSTS agents must be able to connect to both the functions & APIM through ARM.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi -ne $null -and $newapi.indexOf("/apis/")-ne -1)
- {
- $newapi=$newapi.Substring($newapi.indexOf("/apis")+6)
- }
- $v=Get-VstsInput -Name version
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name APIResourceGroupName
- $functiongroup=Get-VstsInput -Name ResourceGroupName
- $functionsite=Get-VstsInput -Name HostingWebSite
- $product=Get-VstsInput -Name product1
-
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $functionbaseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($functiongroup)/providers/Microsoft.Web/sites/$($functionsite)"
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- $bodyadmin="resource=https%3A%2F%2Fmanagement.core.windows.net%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- $coremgt=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $bodyadmin| ConvertFrom-Json
-
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $adminscmheaders = @{
- Authorization = "Bearer $($coremgt.access_token)"
- }
- $adminresp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions/admin/token?api-version=2016-08-01" -Headers $headers
- $admintoken=$adminresp.Content|ConvertFrom-Json
- $adminheaders = @{
- Authorization = "Bearer $($admintoken)"
- }
- $json='{"swagger":{"enabled":true}}'
- Write-Host "Enabling Swagger for the target function set"
- Invoke-WebRequest -Body $json -UseBasicParsing "https://$($functionsite).scm.azurewebsites.net/api/functions/config" -Headers $adminscmheaders -Method Put -ContentType "application/json"
- #generating swagger key
- Write-Host "generating swagger key"
- $key=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey" -Method Post -Headers $adminheaders
- $keyjson=$key.Content|ConvertFrom-Json
- #noticed that calling the swagger definition too fast after getting a new key causes a 500 exception
- Start-Sleep -Seconds 2
- #non default swagger
-
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- Write-Host "downloading swagger definition https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString("https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)")
- $cli.Dispose()
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/api-version-sets/$($version)?api-version=2017-03-01"
- $json='{"id":"/api-version-sets/'+$($version)+'","name":"'+$($newapi)+'","versioningScheme":"Segment"}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- {
- "displayName":"'+$($newapi)+'",
- "path":"'+$($newapi)+'",
- "protocols":["https"],
- "apiVersion":"v1",
- "apiVersionSet":{
- "id":"/api-version-sets/'+$($version)+'",
- "name":"'+$($newapi)+'",
- "versioningScheme":"Segment"
- },
- "apiVersionSetId":"/api-version-sets/'+$version+'"
- }
- }'
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $headers.Add("If-Match","*")
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else
- {
- #the apis already exists, only a new version must be created.
-
- $newversionurl="$($baseurl)/apis/$($newapi)$($v);rev=1?api-version=2017-03-01"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json='{"sourceApiId":"/apis/'+$($newapi)+'","apiVersionName":"'+$($v)+'","apiVersionSet":{"versioningScheme":"Segment"}}'
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
-
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/vnd.ms-azure-apim.revisioninfo+json" -Body $json -Headers $headers
- $importurl="$($baseurl)/apis/$($newapi)$($v)?import=true&api-version=2017-03-01"
- }
- else
- {
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
- }
- $headers.Add("If-Match","*")
- #reapplying swagger
-
-
- Write-Host "Importing swagger $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
- if($newversionurl -eq $null -or $newversionurl -eq "" -or ($currentversion -eq $v))
- {
- $apimv="$($newapi)"
- }
- else
- {
- $apimv="$($newapi)$($v)"
- }
-
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apimv)?api-version=2017-03-01"
-
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$apimv/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-
-
- Write-Host "iterating through operations $($baseurl)/apis/$($apimv)/operations?api-version=2017-03-01"
- $operationresponse=Invoke-WebRequest -UseBasicParsing "$($baseurl)/apis/$($apimv)/operations?api-version=2017-03-01" -Headers $headers
- $operations = $operationresponse.Content|ConvertFrom-Json
- $ops = @{}
- $operations.value|%{
- $ops.Add($_.properties.displayName,$_.name)
- }
- Write-Host "iterating through fucntions $($functionbaseurl)/functions?api-version=2016-08-01"
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions?api-version=2016-08-01" -Headers $headers
- $functions = $resp.Content|ConvertFrom-Json
-
- $functions.value|% {
- $fname=$_.name.Substring($_.name.IndexOf("/")+1)
- Write-Host "Getting function keys https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys"
- $keys=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys" -Headers $adminheaders
- $keys=$keys.Content|ConvertFrom-Json
- $thekey=$keys.keys[0].value
- $ops.Keys|%{
- if($_.ToString().indexOf("$fname/") -ne -1)
- {
- $targetfname=$ops[$_.ToString()]
- $json = "
-
- "+$thekey+"
-
-
-
-
-
-
-
-
-
-
-
-"
- Write-Host "setting operation policy $($baseurl)/apis/$($apimv)/operations/$($targetfname)/policy?api-version=2017-03-01"
- Invoke-WebRequest -Headers $headers -UseBasicParsing -Uri "$($baseurl)/apis/$($apimv)/operations/$($targetfname)/policy?api-version=2017-03-01" -Method Put -Body $json -ContentType "application/vnd.ms-azure-apim.policy.raw+xml"
- }
- }
-
-}
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/icon.png b/apimfunctionversioned/v1/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimfunctionversioned/v1/icon.png and /dev/null differ
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/module.json b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/lib.json b/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimfunctionversioned/v1/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimfunctionversioned/v1/task.json b/apimfunctionversioned/v1/task.json
deleted file mode 100644
index 5eb033f..0000000
--- a/apimfunctionversioned/v1/task.json
+++ /dev/null
@@ -1,240 +0,0 @@
-{
- "id": "1d7773b6-c5d2-4173-b687-5aadbae3d2ea",
- "name": "apimfunctionversioned",
- "friendlyName": "API Management - Create or Update versioned API on Azure Functions",
- "description": "API Management - Create or Update versioned API on Azure Functions",
- "author": "Stephane Eyskens",
- "helpMarkDown": "Create or Update versioned API on Azure Functions",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update versioned API on Function $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "APIResourceGroupName",
- "label": "API Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal"
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "false"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "API Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "False"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": true,
- "helpMarkDown": "API version",
- "defaultValue": "v1"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "CacheLookup",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "ResourceGroupName",
- "label": "Functions Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the Azure Functions"
- },
- {
- "name": "HostingWebSite",
- "type": "pickList",
- "label": "Functions Site",
- "required": true,
- "helpMarkDown": "Web site where your functions are deployed",
- "properties": {
- "EditableOptions": "true"
- }
- }
-
- ],
-
- "dataSourceBindings": [
- {
- "target": "APIResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(APIResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "HostingWebSite",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.Web/sites?api-version=2016-08-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{{{name}}}"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimfunctionversioned.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/apimfunctionversioned.ps1 b/apimfunctionversioned/v2/apimfunctionversioned.ps1
deleted file mode 100644
index ead09f1..0000000
--- a/apimfunctionversioned/v2/apimfunctionversioned.ps1
+++ /dev/null
@@ -1,348 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against an Azure Function set.
-Prerequisite to using this task: VSTS agents must be able to connect to both the functions & APIM through ARM.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi -ne $null -and $newapi.indexOf("/apis/")-ne -1)
- {
- $newapi=$newapi.Substring($newapi.indexOf("/apis")+6)
- }
- $v=Get-VstsInput -Name version
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name APIResourceGroupName
- $functiongroup=Get-VstsInput -Name ResourceGroupName
- $functionsite=Get-VstsInput -Name HostingWebSite
- $product=Get-VstsInput -Name product1
- $path = Get-VstsInput -Name pathapi
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $functionbaseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($functiongroup)/providers/Microsoft.Web/sites/$($functionsite)"
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- $bodyadmin="resource=https%3A%2F%2Fmanagement.core.windows.net%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- $coremgt=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $bodyadmin| ConvertFrom-Json
-
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $adminscmheaders = @{
- Authorization = "Bearer $($coremgt.access_token)"
- }
- $adminresp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions/admin/token?api-version=2016-08-01" -Headers $headers
- $admintoken=$adminresp.Content|ConvertFrom-Json
- $adminheaders = @{
- Authorization = "Bearer $($admintoken)"
- }
- $json='{"swagger":{"enabled":true}}'
- Write-Host "Enabling Swagger for the target function set"
- Invoke-WebRequest -Body $json -UseBasicParsing "https://$($functionsite).scm.azurewebsites.net/api/functions/config" -Headers $adminscmheaders -Method Put -ContentType "application/json"
- #generating swagger key
- Write-Host "generating swagger key"
- $key=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey" -Method Post -Headers $adminheaders
- $keyjson=$key.Content|ConvertFrom-Json
- #noticed that calling the swagger definition too fast after getting a new key causes a 500 exception
- Start-Sleep -Seconds 2
- #non default swagger
-
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- Write-Host "downloading swagger definition https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString("https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)")
- $cli.Dispose()
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/api-version-sets/$($version)?api-version=2017-03-01"
- $json='{"id":"/api-version-sets/'+$($version)+'","name":"'+$($newapi)+'","versioningScheme":"Segment"}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- {
- "displayName":"'+$($newapi)+'",
- "path":"'+$($path)+'",
- "protocols":["https"],
- "apiVersion":"v1",
- "apiVersionSet":{
- "id":"/api-version-sets/'+$($version)+'",
- "name":"'+$($newapi)+'",
- "versioningScheme":"Segment"
- },
- "apiVersionSetId":"/api-version-sets/'+$version+'"
- }
- }'
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $headers.Add("If-Match","*")
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else
- {
- #the apis already exists, only a new version must be created.
-
- $newversionurl="$($baseurl)/apis/$($newapi)$($v);rev=1?api-version=2017-03-01"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json='{"sourceApiId":"/apis/'+$($newapi)+'","apiVersionName":"'+$($v)+'","apiVersionSet":{"versioningScheme":"Segment"}}'
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
-
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/vnd.ms-azure-apim.revisioninfo+json" -Body $json -Headers $headers
- $importurl="$($baseurl)/apis/$($newapi)$($v)?import=true&api-version=2017-03-01"
- }
- else
- {
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
- }
- $headers.Add("If-Match","*")
- #reapplying swagger
-
-
- Write-Host "Importing swagger $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
- if($newversionurl -eq $null -or $newversionurl -eq "" -or ($currentversion -eq $v))
- {
- $apimv="$($newapi)"
- }
- else
- {
- $apimv="$($newapi)$($v)"
- }
-
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apimv)?api-version=2017-03-01"
-
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$apimv/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-
-
- Write-Host "iterating through operations $($baseurl)/apis/$($apimv)/operations?api-version=2017-03-01"
- $operationresponse=Invoke-WebRequest -UseBasicParsing "$($baseurl)/apis/$($apimv)/operations?api-version=2017-03-01" -Headers $headers
- $operations = $operationresponse.Content|ConvertFrom-Json
- $ops = @{}
- $operations.value|%{
- $ops.Add($_.properties.displayName,$_.name)
- }
- Write-Host "iterating through fucntions $($functionbaseurl)/functions?api-version=2016-08-01"
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions?api-version=2016-08-01" -Headers $headers
- $functions = $resp.Content|ConvertFrom-Json
-
- $functions.value|% {
- $fname=$_.name.Substring($_.name.IndexOf("/")+1)
- Write-Host "Getting function keys https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys"
- $keys=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys" -Headers $adminheaders
- $keys=$keys.Content|ConvertFrom-Json
- $thekey=$keys.keys[0].value
- $ops.Keys|%{
- if($_.ToString().indexOf("$fname/") -ne -1)
- {
- $targetfname=$ops[$_.ToString()]
- $json = "
-
- "+$thekey+"
-
-
-
-
-
-
-
-
-
-
-
-"
- Write-Host "setting operation policy $($baseurl)/apis/$($apimv)/operations/$($targetfname)/policy?api-version=2017-03-01"
- Invoke-WebRequest -Headers $headers -UseBasicParsing -Uri "$($baseurl)/apis/$($apimv)/operations/$($targetfname)/policy?api-version=2017-03-01" -Method Put -Body $json -ContentType "application/vnd.ms-azure-apim.policy.raw+xml"
- }
- }
-
-}
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/icon.png b/apimfunctionversioned/v2/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimfunctionversioned/v2/icon.png and /dev/null differ
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/module.json b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Minimatch.dll b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/lib.json b/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimfunctionversioned/v2/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimfunctionversioned/v2/task.json b/apimfunctionversioned/v2/task.json
deleted file mode 100644
index be9a155..0000000
--- a/apimfunctionversioned/v2/task.json
+++ /dev/null
@@ -1,300 +0,0 @@
-{
- "id": "1d7773b6-c5d2-4173-b687-5aadbae3d2ea",
- "name": "apimfunctionversioned",
- "friendlyName": "API Management - Create or Update versioned API on Azure Functions(v1)",
- "description": "API Management - Create or Update versioned API on Azure Functions(v1)",
- "author": "Stephane Eyskens",
- "helpMarkDown": "Create or Update versioned API on Azure Functions(v1)",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "2",
- "Minor": "0",
- "Patch": "5"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update versioned API on Function(v1) $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "APIResourceGroupName",
- "label": "API Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "API Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": true,
- "helpMarkDown": "API version",
- "defaultValue": "v1"
- },
- {
- "name": "scheme",
- "type": "pickList",
- "label": "Versioning scheme",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Path",
- "options": {
- "Path": "Path",
- "Header":"Header",
- "Query":"Query String"
- },
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "version=v1"
- },
- {
- "name": "VersionHeader",
- "type": "string",
- "label": "Version Header",
- "required": true,
- "helpMarkDown": "Version Header",
- "defaultValue": "Api-Version",
- "visibleRule": "scheme = Header && version=v1"
- },
- {
- "name": "QueryParam",
- "type": "string",
- "label": "Version query parameter",
- "required": true,
- "helpMarkDown": "Version query parameter",
- "defaultValue": "api-version",
- "visibleRule": "scheme = Query && version=v1"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": false,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "ResourceGroupName",
- "label": "Functions Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the Azure Functions",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "HostingWebSite",
- "type": "pickList",
- "label": "Functions Site",
- "required": true,
- "helpMarkDown": "Web site where your functions are deployed",
- "properties": {
- "EditableOptions": "true"
- }
- }
-
- ],
-
- "dataSourceBindings": [
- {
- "target": "APIResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(APIResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "HostingWebSite",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.Web/sites?api-version=2016-08-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{{{name}}}"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimfunctionversioned.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/apimfunctionversioned.ps1 b/apimfunctionversioned/v3/apimfunctionversioned.ps1
deleted file mode 100644
index 1f0bf10..0000000
--- a/apimfunctionversioned/v3/apimfunctionversioned.ps1
+++ /dev/null
@@ -1,359 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against an Azure Function set.
-Prerequisite to using this task: VSTS agents must be able to connect to both the functions & APIM through ARM.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi -ne $null -and $newapi.indexOf("/apis/")-ne -1)
- {
- $newapi=$newapi.Substring($newapi.indexOf("/apis")+6)
- }
- $v=Get-VstsInput -Name version
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name APIResourceGroupName
- $functiongroup=Get-VstsInput -Name ResourceGroupName
- $functionsite=Get-VstsInput -Name HostingWebSite
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $path = Get-VstsInput -Name pathapi
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $functionbaseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($functiongroup)/providers/Microsoft.Web/sites/$($functionsite)"
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- $bodyadmin="resource=https%3A%2F%2Fmanagement.core.windows.net%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- $coremgt=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $bodyadmin| ConvertFrom-Json
-
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $adminscmheaders = @{
- Authorization = "Bearer $($coremgt.access_token)"
- }
- $adminresp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions/admin/token?api-version=2016-08-01" -Headers $headers
- $admintoken=$adminresp.Content|ConvertFrom-Json
- $adminheaders = @{
- Authorization = "Bearer $($admintoken)"
- }
- $json='{"swagger":{"enabled":true}}'
- Write-Host "Enabling Swagger for the target function set"
- Invoke-WebRequest -Body $json -UseBasicParsing "https://$($functionsite).scm.azurewebsites.net/api/functions/config" -Headers $adminscmheaders -Method Put -ContentType "application/json"
- #generating swagger key
- Write-Host "generating swagger key"
- $key=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/host/systemkeys/swaggerdocumentationkey" -Method Post -Headers $adminheaders
- $keyjson=$key.Content|ConvertFrom-Json
- #noticed that calling the swagger definition too fast after getting a new key causes a 500 exception
- Start-Sleep -Seconds 2
- #non default swagger
-
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- Write-Host "downloading swagger definition https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)"
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString("https://$($functionsite).azurewebsites.net/admin/host/swagger/default?code=$($keyjson.value)")
- $cli.Dispose()
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/api-version-sets/$($version)?api-version=2017-03-01"
- $json='{"id":"/api-version-sets/'+$($version)+'","name":"'+$($newapi)+'","versioningScheme":"Segment"}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- {
- "displayName":"'+$($newapi)+'",
- "path":"'+$($path)+'",
- "protocols":["https"],
- "apiVersion":"v1",
- "apiVersionSet":{
- "id":"/api-version-sets/'+$($version)+'",
- "name":"'+$($newapi)+'",
- "versioningScheme":"Segment"
- },
- "apiVersionSetId":"/api-version-sets/'+$version+'"
- }
- }'
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $headers.Add("If-Match","*")
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else
- {
- #the apis already exists, only a new version must be created.
-
- $newversionurl="$($baseurl)/apis/$($newapi)$($v);rev=1?api-version=2017-03-01"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json='{"sourceApiId":"/apis/'+$($newapi)+'","apiVersionName":"'+$($v)+'","apiVersionSet":{"versioningScheme":"Segment"}}'
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
-
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/vnd.ms-azure-apim.revisioninfo+json" -Body $json -Headers $headers
- $importurl="$($baseurl)/apis/$($newapi)$($v)?import=true&api-version=2017-03-01"
- }
- else
- {
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
- }
- $headers.Add("If-Match","*")
- #reapplying swagger
-
-
- Write-Host "Importing swagger $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- if($newversionurl -eq $null -or $newversionurl -eq "" -or ($currentversion -eq $v))
- {
- $apimv="$($newapi)"
- }
- else
- {
- $apimv="$($newapi)$($v)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apimv)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$apimv/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-
-
- Write-Host "iterating through operations $($baseurl)/apis/$($apimv)/operations?api-version=2017-03-01"
- $operationresponse=Invoke-WebRequest -UseBasicParsing "$($baseurl)/apis/$($apimv)/operations?api-version=2017-03-01" -Headers $headers
- $operations = $operationresponse.Content|ConvertFrom-Json
- $ops = @{}
- $operations.value|%{
- $ops.Add($_.properties.displayName,$_.name)
- }
- Write-Host "iterating through fucntions $($functionbaseurl)/functions?api-version=2016-08-01"
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($functionbaseurl)/functions?api-version=2016-08-01" -Headers $headers
- $functions = $resp.Content|ConvertFrom-Json
-
- $functions.value|% {
- $fname=$_.name.Substring($_.name.IndexOf("/")+1)
- Write-Host "Getting function keys https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys"
- $keys=Invoke-WebRequest -UseBasicParsing -Uri "https://$($functionsite).azurewebsites.net/admin/functions/$($fname)/keys" -Headers $adminheaders
- $keys=$keys.Content|ConvertFrom-Json
- $thekey=$keys.keys[0].value
- $ops.Keys|%{
- if($_.ToString().indexOf("$fname/") -ne -1)
- {
- $targetfname=$ops[$_.ToString()]
- $json = "
-
- "+$thekey+"
-
-
-
-
-
-
-
-
-
-
-
-"
- Write-Host "setting operation policy $($baseurl)/apis/$($apimv)/operations/$($targetfname)/policy?api-version=2017-03-01"
- Invoke-WebRequest -Headers $headers -UseBasicParsing -Uri "$($baseurl)/apis/$($apimv)/operations/$($targetfname)/policy?api-version=2017-03-01" -Method Put -Body $json -ContentType "application/vnd.ms-azure-apim.policy.raw+xml"
- }
- }
-
-}
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/icon.png b/apimfunctionversioned/v3/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimfunctionversioned/v3/icon.png and /dev/null differ
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/module.json b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Minimatch.dll b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/lib.json b/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimfunctionversioned/v3/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimfunctionversioned/v3/task.json b/apimfunctionversioned/v3/task.json
deleted file mode 100644
index 417553f..0000000
--- a/apimfunctionversioned/v3/task.json
+++ /dev/null
@@ -1,300 +0,0 @@
-{
- "id": "1d7773b6-c5d2-4173-b687-5aadbae3d2ea",
- "name": "apimfunctionversioned",
- "friendlyName": "API Management - Create or Update versioned API on Azure Functions(v1)",
- "description": "API Management - Create or Update versioned API on Azure Functions(v1)",
- "author": "Stephane Eyskens",
- "helpMarkDown": "Create or Update versioned API on Azure Functions(v1)",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "3",
- "Minor": "0",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update versioned API on Function(v1) $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "APIResourceGroupName",
- "label": "API Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": true,
- "helpMarkDown": "API version",
- "defaultValue": "v1"
- },
- {
- "name": "scheme",
- "type": "pickList",
- "label": "Versioning scheme",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Path",
- "options": {
- "Path": "Path",
- "Header":"Header",
- "Query":"Query String"
- },
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "version=v1"
- },
- {
- "name": "VersionHeader",
- "type": "string",
- "label": "Version Header",
- "required": true,
- "helpMarkDown": "Version Header",
- "defaultValue": "Api-Version",
- "visibleRule": "scheme = Header && version=v1"
- },
- {
- "name": "QueryParam",
- "type": "string",
- "label": "Version query parameter",
- "required": true,
- "helpMarkDown": "Version query parameter",
- "defaultValue": "api-version",
- "visibleRule": "scheme = Query && version=v1"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": false,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "ResourceGroupName",
- "label": "Functions Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the Azure Functions",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "HostingWebSite",
- "type": "pickList",
- "label": "Functions Site",
- "required": true,
- "helpMarkDown": "Web site where your functions are deployed",
- "properties": {
- "EditableOptions": "true"
- }
- }
-
- ],
-
- "dataSourceBindings": [
- {
- "target": "APIResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(APIResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(APIResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "HostingWebSite",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.Web/sites?api-version=2016-08-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{{{name}}}"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimfunctionversioned.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimfunctionversioned/v4/task.json b/apimfunctionversioned/v4/task.json
index 4e75a8d..df3fcd3 100644
--- a/apimfunctionversioned/v4/task.json
+++ b/apimfunctionversioned/v4/task.json
@@ -1,5 +1,5 @@
{
- "id": "1d7773b6-c5d2-4173-b687-5aadbae3d2ea",
+ "id": "a3b41a7b-b05b-4f81-853e-569f32ccaab4",
"name": "apimfunctionversioned",
"friendlyName": "API Management - Create or Update versioned API on Azure Functions(v1)",
"description": "API Management - Create or Update versioned API on Azure Functions(v1)",
diff --git a/apimglobalpolicy/v1/apimglobalpolicy.ps1 b/apimglobalpolicy/v1/apimglobalpolicy.ps1
deleted file mode 100644
index e07236b..0000000
--- a/apimglobalpolicy/v1/apimglobalpolicy.ps1
+++ /dev/null
@@ -1,110 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
- #getting inputs
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
-
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- #preparing endpoints
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $policyapiurl= "$($baseurl)/policies/policy?api-version=2018-06-01-preview"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Creating or updating global policy $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/icon.png b/apimglobalpolicy/v1/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimglobalpolicy/v1/icon.png and /dev/null differ
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/module.json b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/lib.json b/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimglobalpolicy/v1/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimglobalpolicy/v1/task.json b/apimglobalpolicy/v1/task.json
deleted file mode 100644
index 74293b5..0000000
--- a/apimglobalpolicy/v1/task.json
+++ /dev/null
@@ -1,162 +0,0 @@
-{
- "id": "10e68a6e-a7d7-4f5d-9911-54cf82e989b4",
- "name": "apimglobalpolicy",
- "friendlyName": "API Management - Create or Update a Global Policy",
- "description": "API Management - Create or Update a Global Policy",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create or Update a Global Policy",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "2"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create or Update a Global Policy $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimglobalpolicy.ps1"
- }
- }
-}
diff --git a/apimglobalpolicy/v2/task.json b/apimglobalpolicy/v2/task.json
index 1e285d4..c8c674f 100644
--- a/apimglobalpolicy/v2/task.json
+++ b/apimglobalpolicy/v2/task.json
@@ -1,5 +1,5 @@
{
- "id": "10e68a6e-a7d7-4f5d-9911-54cf82e989b4",
+ "id": "a2cc613a-f6fb-4c90-acae-832e292c384c",
"name": "apimglobalpolicy",
"friendlyName": "API Management - Create or Update a Global Policy",
"description": "API Management - Create or Update a Global Policy",
diff --git a/apimoperationpolicies/v3/apimoperationpolicies.ps1 b/apimoperationpolicies/v3/apimoperationpolicies.ps1
deleted file mode 100644
index 80ef512..0000000
--- a/apimoperationpolicies/v3/apimoperationpolicies.ps1
+++ /dev/null
@@ -1,108 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an APIM product.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $api=Get-VstsInput -Name ApiName
- $operation=Get-VstsInput -Name OperationName
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
-
- if($SelectedTemplate -eq "RateAndQuota")
- {
- $PolicyContent = Get-VstsInput -Name RateAndQuota
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($api)/operations/$($operation)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/icon.png b/apimoperationpolicies/v3/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimoperationpolicies/v3/icon.png and /dev/null differ
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/module.json b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Minimatch.dll b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/lib.json b/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimoperationpolicies/v3/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimoperationpolicies/v3/task.json b/apimoperationpolicies/v3/task.json
deleted file mode 100644
index e26bd4a..0000000
--- a/apimoperationpolicies/v3/task.json
+++ /dev/null
@@ -1,219 +0,0 @@
-{
- "id": "a67d9016-264e-4df8-b47e-85ea302d09b3",
- "name": "apimoperationpolicies",
- "friendlyName": "API Management - Set or update an operation policy",
- "description": "API Management - Set or update an operation policy",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Set or update an operation policy",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "3",
- "Minor": "0",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Set or update an operation policy $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiName",
- "type": "pickList",
- "label": "API",
- "required": true,
- "helpMarkDown": "The API you want to list operations",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "OperationName",
- "type": "pickList",
- "label": "Operation",
- "required": true,
- "helpMarkDown": "The operation you want to set or create policy",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the operation. Make sure you type in valid XML and to adjust it to your needs.",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "Basic": "Basic",
- "Custom": "Custom",
- "JWT": "JWT",
- "IP": "IP",
- "RateAndQuota": "RateAndQuota",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateAndQuota",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateAndQuota"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t< calls='10000' bandwidth='40000' counter-key='@(context.Request.IpAddress)' renewal-period='3600'/>\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "name": "Apis",
- "target": "ApiName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ServiceName)/apis?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)",
- "ServiceName": "$(ApiPortalName)"
- }
- },
- {
- "name": "Operations",
- "target": "OperationName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ServiceName)/apis/$(ApiId)/operations?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)",
- "ServiceName": "$(ApiPortalName)",
- "ApiId": "$(ApiName)"
- }
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimoperationpolicies.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/apimoperationpolicies.ps1 b/apimoperationpolicies/v4/apimoperationpolicies.ps1
deleted file mode 100644
index 1504e86..0000000
--- a/apimoperationpolicies/v4/apimoperationpolicies.ps1
+++ /dev/null
@@ -1,127 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates an APIM product.
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $api=Get-VstsInput -Name ApiName
- $operation=Get-VstsInput -Name OperationName
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- $CurrentRevision=Get-VstsInput -Name CurrentRevision
- if($SelectedTemplate -eq "RateAndQuota")
- {
- $PolicyContent = Get-VstsInput -Name RateAndQuota
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $RevisionUrl="$($baseurl)/apis/$($api)/revisions?api-version=2019-01-01"
- Write-Host "Revision Url is $($RevisionUrl)"
- $revisions=Invoke-WebRequest -UseBasicParsing -Uri $RevisionUrl -Headers $headers|ConvertFrom-Json
- if($CurrentRevision -eq $true)
- {
-
- $revisions|% {
- $_.value|%{
- if($_.isCurrent -eq $true)
- {
- $rev=$_.apiRevision
- }
- }
- }
- }
- else {
- $rev=$revisions.count
- }
- Write-Host "Revision to patch is $($rev)"
- $policyapiurl= "$($baseurl)/apis/$($api);rev=$($rev)/operations/$($operation)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/icon.png b/apimoperationpolicies/v4/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimoperationpolicies/v4/icon.png and /dev/null differ
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/module.json b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Minimatch.dll b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/lib.json b/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimoperationpolicies/v4/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimoperationpolicies/v4/task.json b/apimoperationpolicies/v4/task.json
deleted file mode 100644
index 890f7e7..0000000
--- a/apimoperationpolicies/v4/task.json
+++ /dev/null
@@ -1,226 +0,0 @@
-{
- "id": "a67d9016-264e-4df8-b47e-85ea302d09b3",
- "name": "apimoperationpolicies",
- "friendlyName": "API Management - Set or update an operation policy",
- "description": "API Management - Set or update an operation policy",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Set or update an operation policy",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "4",
- "Minor": "0",
- "Patch": "0"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Set or update an operation policy $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiName",
- "type": "pickList",
- "label": "API",
- "required": true,
- "helpMarkDown": "The API you want to list operations",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "OperationName",
- "type": "pickList",
- "label": "Operation",
- "required": true,
- "helpMarkDown": "The operation you want to set or create policy",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "CurrentRevision",
- "type": "boolean",
- "label": "Use current revision",
- "helpMarkDown": "When set to false, the operation-level policy is applied to the last revision, else to the current one, so directly impacting consumers",
- "defaultValue":false
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the operation. Make sure you type in valid XML and to adjust it to your needs.",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "Basic": "Basic",
- "Custom": "Custom",
- "JWT": "JWT",
- "IP": "IP",
- "RateAndQuota": "RateAndQuota",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "Basic",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "JWT",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateAndQuota",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateAndQuota"
- },
- {
- "name": "RateByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t< calls='10000' bandwidth='40000' counter-key='@(context.Request.IpAddress)' renewal-period='3600'/>\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiline",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "name": "Apis",
- "target": "ApiName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ServiceName)/apis?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{name}}}\" }",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)",
- "ServiceName": "$(ApiPortalName)"
- }
- },
- {
- "name": "Operations",
- "target": "OperationName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ServiceName)/apis/$(ApiId)/operations?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)",
- "ServiceName": "$(ApiPortalName)",
- "ApiId": "$(ApiName)"
- }
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimoperationpolicies.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimoperationpolicies/v5/task.json b/apimoperationpolicies/v5/task.json
index 724f013..fb73374 100644
--- a/apimoperationpolicies/v5/task.json
+++ b/apimoperationpolicies/v5/task.json
@@ -1,5 +1,5 @@
{
- "id": "a67d9016-264e-4df8-b47e-85ea302d09b3",
+ "id": "70c613c8-8ef7-448f-b843-b6ff001d2aa2",
"name": "apimoperationpolicies",
"friendlyName": "API Management - Set or update an operation policy",
"description": "API Management - Set or update an operation policy",
diff --git a/apimreleaserevision/v4/task.json b/apimreleaserevision/v4/task.json
index 99982e8..4f43381 100644
--- a/apimreleaserevision/v4/task.json
+++ b/apimreleaserevision/v4/task.json
@@ -1,5 +1,5 @@
{
- "id": "0f876bf2-e074-4d3a-ad7d-56fa54ba0c70",
+ "id": "719178f6-1608-44e5-9bc2-cbdff55c5bcd",
"name": "apimreleaserevision",
"friendlyName": "API Management - Make Revision Current",
"description": "Set released revision as a current",
diff --git a/apimrestorefromrepository/v3/task.json b/apimrestorefromrepository/v3/task.json
index 852d558..faf31f7 100644
--- a/apimrestorefromrepository/v3/task.json
+++ b/apimrestorefromrepository/v3/task.json
@@ -1,5 +1,5 @@
{
- "id": "c53cf115-5ad9-4c25-a4bc-023e00a3ee8f",
+ "id": "3bdfbdb5-29e2-4372-a4a9-84e5caf9d099",
"name": "apimrestorefromrepository",
"friendlyName": "API Management - Restore API definition from repository",
"description": "API Management - Restore API definition from repository",
diff --git a/apimsavetorepository/v3/task.json b/apimsavetorepository/v3/task.json
index 5b998d6..c6a6946 100644
--- a/apimsavetorepository/v3/task.json
+++ b/apimsavetorepository/v3/task.json
@@ -1,5 +1,5 @@
{
- "id": "c43ec638-91a7-4de6-88e5-8f8f46a58ea9",
+ "id": "15eea4c7-7ffd-46d4-9e58-70181d892fb9",
"name": "apimsavetorepository",
"friendlyName": "API Management - Save API definition to repository",
"description": "API Management - Save API definition to repository",
diff --git a/apimversioned/v1/apimversioned.ps1 b/apimversioned/v1/apimversioned.ps1
deleted file mode 100644
index 1dc8aba..0000000
--- a/apimversioned/v1/apimversioned.ps1
+++ /dev/null
@@ -1,269 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a versioned Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
-
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi=Get-VstsInput -Name targetapi
- if($newapi.startswith("/subscriptions"))
- {
- $newapi=$newapi.substring($newapi.indexOf("/apis")+6)
- }
- $v=Get-VstsInput -Name version
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $product=Get-VstsInput -Name product1
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- Write-Host "checking whether $($targeturl) exists"
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- Write-Host "found api"
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- #downloading swagger for later import
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString($swaggerlocation)
- $cli.Dispose()
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/api-version-sets/$($version)?api-version=2017-03-01"
- $json='{"id":"/api-version-sets/'+$($version)+'","name":"'+$($newapi)+'","versioningScheme":"Segment"}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- {
- "displayName":"'+$($newapi)+'",
- "path":"'+$($newapi)+'",
- "protocols":["https"],
- "apiVersion":"v1",
- "apiVersionSet":{
- "id":"/api-version-sets/'+$($version)+'",
- "name":"'+$($newapi)+'",
- "versioningScheme":"Segment"
- },
- "apiVersionSetId":"/api-version-sets/'+$version+'"
- }
- }'
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $headers.Add("If-Match","*")
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else
- {
- #the api already exists, only a new version must be created.
- $newversionurl="$($baseurl)/apis/$($newapi)$($v);rev=1?api-version=2017-03-01"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json='{"sourceApiId":"/apis/'+$($newapi)+'","apiVersionName":"'+$($v)+'","apiVersionSet":{"versioningScheme":"Segment"}}'
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
- Write-Host "current version $($currentversion), version is $($v), version exists $($versionexists)"
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/vnd.ms-azure-apim.revisioninfo+json" -Body $json -Headers $headers
- $importurl="$($baseurl)/apis/$($newapi)$($v)?import=true&api-version=2017-03-01"
- }
- else
- {
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
- }
- $headers.Add("If-Match","*")
- #reapplying swagger
-
- Write-Host "Importing swagger $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
- if($newversionurl -eq $null -or $newversionurl -eq "" -or ($currentversion -eq $v))
- {
- $apimv="$($newapi)"
- }
- else
- {
- $apimv="$($newapi)$($v)"
- }
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apimv)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($apimv)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimversioned/v1/icon.png b/apimversioned/v1/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimversioned/v1/icon.png and /dev/null differ
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimversioned/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/module.json b/apimversioned/v1/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimversioned/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimversioned/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apimversioned/v1/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimversioned/v1/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimversioned/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimversioned/v1/ps_modules/VstsTaskSdk/lib.json b/apimversioned/v1/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimversioned/v1/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimversioned/v1/task.json b/apimversioned/v1/task.json
deleted file mode 100644
index d43849a..0000000
--- a/apimversioned/v1/task.json
+++ /dev/null
@@ -1,217 +0,0 @@
-{
- "id": "caee5262-b7ce-48c9-b5f7-70c586148ff8",
- "name": "apimversioned",
- "friendlyName": "API Management - Create or Update Versioned API",
- "description": "API Management - Create or Update Versioned API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "3"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal"
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "false"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "False"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "Swagger Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": ""
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": true,
- "helpMarkDown": "API version",
- "defaultValue": "v1"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- }
- },
- {
- "name": "None",
- "type": "string",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "CacheLookup",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "string",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
-
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimversioned.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v2/apimversioned.ps1 b/apimversioned/v2/apimversioned.ps1
deleted file mode 100644
index 81423ba..0000000
--- a/apimversioned/v2/apimversioned.ps1
+++ /dev/null
@@ -1,332 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a versioned Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
-
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $VersionHeader= Get-VstsInput -Name VersionHeader
- $QueryParam = get-VstsInput -Name QueryParam
-
- $VersionScheme = Get-VstsInput -Name scheme
- switch($VersionScheme)
- {
- "Path" {$scheme='"versioningScheme":"Segment"'}
- "Query" {$scheme='"versioningScheme":"Query","versionQueryName":"'+$($QueryParam)+'"'}
- "Header" {$scheme='"versioningScheme":"Header","versionHeaderName":"'+$($VersionHeader)+'"'}
- }
- $newapi=Get-VstsInput -Name targetapi
- if($newapi.startswith("/subscriptions"))
- {
- $newapi=$newapi.substring($newapi.indexOf("/apis")+6)
- }
- $v=Get-VstsInput -Name version
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SwaggerPicker = Get-VstsInput -Name SwaggerPicker
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $swaggercode=Get-VstsInput -Name swaggercode
- $swaggerartifact = Get-VstsInput -Name swaggerartifact
- $product=Get-VstsInput -Name product1
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $path = Get-VstsInput -Name pathapi
- $Authorization = Get-VstsInput -Name Authorization
- $oid = Get-VstsInput -Name oid
- $oauth = Get-VstsInput -Name oauth
- $AuthorizationBits='"authenticationSettings":null'
- switch($Authorization)
- {
- 'OAuth' {$AuthorizationBits='"authenticationSettings":{"oAuth2":{"authorizationServerId":"'+$oauth+'","scope":null}}'}
- 'OpenID' {$AuthorizationBits='"authenticationSettings":{"openid":{"openidProviderId":"'+$oid+'"}}'}
-
- }
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- Write-Host "checking whether $($targeturl) exists"
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- Write-Host "found api"
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- switch($SwaggerPicker)
- {
- "Url" {
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString($swaggerlocation)
- $cli.Dispose()
- }
- "Artifact" {
- try {
- Assert-VstsPath -LiteralPath $swaggerartifact -PathType Leaf
- $swagger = Get-Content "$($swaggerartifact)"
- } catch {
- Write-Error "Invalid file location $($swaggerartifact)"
- }
- }
- "Code" {
- $swagger=$swaggercode
- }
- default {Write-Error "Invalid swagger definition"}
- }
-
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/api-version-sets/$($version)?api-version=2017-03-01"
- $json='{"id":"/api-version-sets/'+$($version)+'","name":"'+$($newapi)+'",'+$($scheme)+'}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- {
- "displayName":"'+$($newapi)+'",'+$AuthorizationBits+',
- "path":"'+$($path)+'",
- "protocols":["https"],
- "apiVersion":"'+$($v)+'",
- "apiVersionSet":{
- "id":"/api-version-sets/'+$($version)+'",
- "name":"'+$($newapi)+'",'+$($scheme)+'
-
- },
- "apiVersionSetId":"/api-version-sets/'+$version+'"
- }
- }'
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $headers.Add("If-Match","*")
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else
- {
- #the api already exists, only a new version must be created.
- $newversionurl="$($baseurl)/apis/$($newapi)$($v);rev=1?api-version=2017-03-01"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json='{"sourceApiId":"/apis/'+$($newapi)+'","apiVersionName":"'+$($v)+'","apiVersionSet":{'+$($scheme)+'}}'
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
- Write-Host "current version $($currentversion), version is $($v), version exists $($versionexists)"
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/vnd.ms-azure-apim.revisioninfo+json" -Body $json -Headers $headers
- $importurl="$($baseurl)/apis/$($newapi)$($v)?import=true&api-version=2017-03-01"
- $authurl = "$($baseurl)/apis/$($newapi)$($v)?api-version=2018-01-01"
- }
- else
- {
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=2017-03-01"
- if($currentversion -ne $v)
- {
- $authurl = "$($baseurl)/apis/$($newapi)$($v)?api-version=2018-01-01"
- }
- else {
- $authurl = "$($baseurl)/apis/$($newapi)?api-version=2018-01-01"
- }
-
- }
- $headers.Add("If-Match","*")
- Write-Host "applying authorization"
-
- $json='{"name":"'+$newapi+'","properties":{'+$AuthorizationBits+',"apiVersion":"'+$v+'"}}'
- Write-Host "Authorization json $($json)"
- Write-Host "endpoint is $($authurl) headers are $($headers)"
- Invoke-WebRequest -UseBasicParsing -Uri $authurl -Headers $headers -Method "PATCH" -ContentType "application/json" -Body $json
- Write-Host "applied authorization"
- #reapplying swagger
-
- Write-Host "Importing swagger $($importurl)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
- if($newversionurl -eq $null -or $newversionurl -eq "" -or ($currentversion -eq $v))
- {
- $apimv="$($newapi)"
- }
- else
- {
- $apimv="$($newapi)$($v)"
- }
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apimv)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($apimv)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host "Setting up authorization"
-
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimversioned/v2/icon.png b/apimversioned/v2/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimversioned/v2/icon.png and /dev/null differ
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimversioned/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/module.json b/apimversioned/v2/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimversioned/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimversioned/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Minimatch.dll b/apimversioned/v2/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimversioned/v2/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimversioned/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimversioned/v2/ps_modules/VstsTaskSdk/lib.json b/apimversioned/v2/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimversioned/v2/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimversioned/v2/task.json b/apimversioned/v2/task.json
deleted file mode 100644
index 7e0f1ea..0000000
--- a/apimversioned/v2/task.json
+++ /dev/null
@@ -1,360 +0,0 @@
-{
- "id": "caee5262-b7ce-48c9-b5f7-70c586148ff8",
- "name": "apimversioned",
- "friendlyName": "API Management - Create or Update Versioned API",
- "description": "API Management - Create or Update Versioned API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "2",
- "Minor": "3",
- "Patch": "3"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "Authorization",
- "type": "pickList",
- "label": "Authorization",
- "required": true,
- "helpMarkDown": "Enable Authorization for the developer portal",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "OAuth":"OAuth",
- "OpenID":"OpenID Connect"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "oauth",
- "type": "pickList",
- "label": "Authorization server",
- "required": false,
- "helpMarkDown": "Authorization server to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OAuth"
- },
- {
- "name": "oid",
- "type": "pickList",
- "label": "OpenID Connect",
- "required": false,
- "helpMarkDown": "OpenID provider to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OpenID"
- },
- {
- "name": "SwaggerPicker",
- "type": "pickList",
- "label": "Swagger location",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Url",
- "options": {
- "Url": "Url",
- "Code":"Code",
- "Artifact":"Build Artifact"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "Swagger Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Url"
- },
- {
- "name": "swaggerartifact",
- "type": "string",
- "label": "Swagger Artifact",
- "required": true,
- "helpMarkDown": "Swagger Artifact. For instance $(System.DefaultWorkingDirectory)/",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Artifact"
- },
- {
- "name": "swaggercode",
- "type": "multiline",
- "label": "Swagger body",
- "required": true,
- "helpMarkDown": "Insert the full swagger definition",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Code"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": true,
- "helpMarkDown": "API version",
- "defaultValue": "v1"
- },
- {
- "name": "scheme",
- "type": "pickList",
- "label": "Versioning scheme",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Path",
- "options": {
- "Path": "Path",
- "Header":"Header",
- "Query":"Query String"
- },
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "version=v1"
- },
- {
- "name": "VersionHeader",
- "type": "string",
- "label": "Version Header",
- "required": true,
- "helpMarkDown": "Version Header",
- "defaultValue": "Api-Version",
- "visibleRule": "scheme = Header && version=v1"
- },
- {
- "name": "QueryParam",
- "type": "string",
- "label": "Version query parameter",
- "required": true,
- "helpMarkDown": "Version query parameter",
- "defaultValue": "api-version",
- "visibleRule": "scheme = Query && version=v1"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": false,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "multiLine",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t \n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oauth",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/authorizationServers?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oid",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/openidConnectProviders?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimversioned.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v3/apimversioned.ps1 b/apimversioned/v3/apimversioned.ps1
deleted file mode 100644
index ba7ac7f..0000000
--- a/apimversioned/v3/apimversioned.ps1
+++ /dev/null
@@ -1,395 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a versioned Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
-
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $VersionHeader= Get-VstsInput -Name VersionHeader
- $QueryParam = get-VstsInput -Name QueryParam
- $VersionScheme = Get-VstsInput -Name scheme
- $MicrosoftApiManagementAPIVersion = Get-VstsInput -Name MicrosoftApiManagementAPIVersion
- switch($VersionScheme)
- {
- "Path" {$scheme='"versioningScheme":"Segment"'}
- "Query" {$scheme='"versioningScheme":"Query","versionQueryName":"'+$($QueryParam)+'"'}
- "Header" {$scheme='"versioningScheme":"Header","versionHeaderName":"'+$($VersionHeader)+'"'}
- }
- $newapi=Get-VstsInput -Name targetapi
- $DisplayName=Get-VstsInput -Name DisplayName
- if($newapi.startswith("/subscriptions"))
- {
- $newapi=$newapi.substring($newapi.indexOf("/apis")+6)
- }
- if([string]::IsNullOrEmpty($DisplayName))
- {
- $DisplayName=$newapi
- }
- $v=Get-VstsInput -Name version
- $apiVersionIdentifier="$($newapi)$($v)" -replace '\.','-'
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SwaggerPicker = Get-VstsInput -Name SwaggerPicker
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $swaggercode=Get-VstsInput -Name swaggercode
- $swaggerartifact = Get-VstsInput -Name swaggerartifact
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $path = Get-VstsInput -Name pathapi
- $Authorization = Get-VstsInput -Name Authorization
- $oid = Get-VstsInput -Name oid
- $oauth = Get-VstsInput -Name oauth
- $OpenAPISpec=Get-VstsInput -Name OpenAPISpec
- $Format=Get-VstsInput -Name Format
- $AuthorizationBits='"authenticationSettings":null'
- Write-Host "Preparing API publishing in $($OpenAPISpec) format $($Format) using Azure API $($MicrosoftApiManagementAPIVersion)"
- switch($Authorization)
- {
- 'OAuth' {$AuthorizationBits='"authenticationSettings":{"oAuth2":{"authorizationServerId":"'+$oauth+'","scope":null}}'}
- 'OpenID' {$AuthorizationBits='"authenticationSettings":{"openid":{"openidProviderId":"'+$oid+'"}}'}
-
- }
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
-
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- Write-Host "checking whether $($targeturl) exists"
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- Write-Host "found api"
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- switch($SwaggerPicker)
- {
- "Url" {
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString($swaggerlocation)
- $cli.Dispose()
-
- }
- "Artifact" {
- try {
- Assert-VstsPath -LiteralPath $swaggerartifact -PathType Leaf
- $swagger = Get-Content "$($swaggerartifact)" -Raw
- } catch {
- Write-Error "Invalid file location $($swaggerartifact)"
- }
- }
- "Code" {
- $swagger=$swaggercode
- }
- default {Write-Error "Invalid swagger definition"}
- }
- if($OpenAPISpec -eq "v3")
- {
- Add-Type -AssemblyName System.Web
- $swagger=$swagger.Replace("`r`n","`n")
- $swagger =[System.Web.HttpUtility]::JavaScriptStringEncode($swagger)
- }
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/api-version-sets/$($version)?api-version=$($MicrosoftApiManagementAPIVersion)"
- $json='{"id":"/api-version-sets/'+$($version)+'","name":"'+$($newapi)+'","displayName":"'+$($DisplayName)+'",'+$($scheme)+'}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- {
- "displayName":"'+$($DisplayName)+'",'+$AuthorizationBits+',
- "path":"'+$($path)+'",
- "protocols":["https"],
- "apiVersion":"'+$($v)+'",
- "apiVersionSet":{
- "id":"/api-version-sets/'+$($version)+'",
- "name":"'+$($newapi)+'",'+$($scheme)+'
- },
- "apiVersionSetId":"/api-version-sets/'+$version+'"
- }
- }'
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $headers.Add("If-Match","*")
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=$($MicrosoftApiManagementAPIVersion)"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- #to change
- if($OpenAPISpec -eq "v2")
- {
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else {
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $openAPIBody='{"contentFormat":"'+$contentFormat+'","contentValue":"'+$swagger+'"}'
- Write-Host "OpenAPI body is $($openAPIBdoy)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/json" -Body $openAPIBody -Headers $headers
- }
-
- }
- else
- {
- #the api already exists, only a new version must be created.
- $newversionurl="$($baseurl)/apis/$($apiVersionIdentifier);rev=1?api-version=$($MicrosoftApiManagementAPIVersion)"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json='{"sourceApiId":"/apis/'+$($newapi)+'","apiVersionName":"'+$($v)+'","apiVersionSet":{'+$($scheme)+'}}'
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
- Write-Host "current version $($currentversion), version is $($v), version exists $($versionexists)"
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/vnd.ms-azure-apim.revisioninfo+json" -Body $json -Headers $headers
- $importurl="$($baseurl)/apis/$($apiVersionIdentifier)?import=true&api-version=$($MicrosoftApiManagementAPIVersion)"
- $authurl = "$($baseurl)/apis/$($apiVersionIdentifier)?api-version=2018-01-01"
- }
- else
- {
-
-
- if($currentversion -ne $v)
- {
- $authurl = "$($baseurl)/apis/$($apiVersionIdentifier)?api-version=2018-01-01"
- $importurl="$($baseurl)/apis/$($apiVersionIdentifier)?import=true&api-version=$($MicrosoftApiManagementAPIVersion)"
- }
- else {
- $authurl = "$($baseurl)/apis/$($newapi)?api-version=2018-01-01"
- $importurl="$($baseurl)/apis/$($newapi)?import=true&api-version=$($MicrosoftApiManagementAPIVersion)"
- }
-
- }
- $headers.Add("If-Match","*")
- Write-Host "applying authorization"
-
- $json='{"name":"'+$newapi+'","properties":{'+$AuthorizationBits+',"apiVersion":"'+$v+'"}}'
- Write-Host "Authorization json $($json)"
- Write-Host "endpoint is $($authurl) headers are $($headers)"
- Invoke-WebRequest -UseBasicParsing -Uri $authurl -Headers $headers -Method "PATCH" -ContentType "application/json" -Body $json
- Write-Host "applied authorization"
- #reapplying swagger
-
- Write-Host "Importing swagger $($importurl) spec is $($OpenAPISpec) format is $($Format)"
-
- if($OpenAPISpec -eq "v2")
- {
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else {
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $openAPIBody='{"contentFormat":"'+$contentFormat+'","contentValue":"'+$swagger+'"}'
- Write-Host "API Body is $($openAPIBody)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/json" -Body $openAPIBody -Headers $headers
-
- }
-
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- if($newversionurl -eq $null -or $newversionurl -eq "" -or ($currentversion -eq $v))
- {
- $apimv="$($newapi)"
- }
- else
- {
- $apimv="$($apiVersionIdentifier)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apimv)?api-version=$($MicrosoftApiManagementAPIVersion)"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($apimv)/policies/policy?api-version=$($MicrosoftApiManagementAPIVersion)"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host "Setting up authorization"
-
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimversioned/v3/icon.png b/apimversioned/v3/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimversioned/v3/icon.png and /dev/null differ
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimversioned/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/module.json b/apimversioned/v3/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimversioned/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimversioned/v3/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Minimatch.dll b/apimversioned/v3/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimversioned/v3/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimversioned/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimversioned/v3/ps_modules/VstsTaskSdk/lib.json b/apimversioned/v3/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimversioned/v3/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimversioned/v3/task.json b/apimversioned/v3/task.json
deleted file mode 100644
index 125f544..0000000
--- a/apimversioned/v3/task.json
+++ /dev/null
@@ -1,408 +0,0 @@
-{
- "id": "caee5262-b7ce-48c9-b5f7-70c586148ff8",
- "name": "apimversioned",
- "friendlyName": "API Management - Create or Update Versioned API",
- "description": "API Management - Create or Update Versioned API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "3",
- "Minor": "3",
- "Patch": "3"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "OpenAPISpec",
- "type": "pickList",
- "label": "OpenAPI Version",
- "required": true,
- "helpMarkDown": "Target Open API version.",
- "defaultValue": "v2",
- "options": {
- "v2": "v2",
- "v3":"v3"
- }
- },
- {
- "name": "Format",
- "type": "pickList",
- "label": "API definition format",
- "required": true,
- "helpMarkDown": "API definition format",
- "defaultValue": "json",
- "options": {
- "json": "json",
- "yaml":"yaml"
- },
- "visibleRule": "OpenAPISpec=v3"
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "Authorization",
- "type": "pickList",
- "label": "Authorization",
- "required": true,
- "helpMarkDown": "Enable Authorization for the developer portal",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "OAuth":"OAuth",
- "OpenID":"OpenID Connect"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "oauth",
- "type": "pickList",
- "label": "Authorization server",
- "required": false,
- "helpMarkDown": "Authorization server to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OAuth"
- },
- {
- "name": "oid",
- "type": "pickList",
- "label": "OpenID Connect",
- "required": false,
- "helpMarkDown": "OpenID provider to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OpenID"
- },
- {
- "name": "SwaggerPicker",
- "type": "pickList",
- "label": "Definition location",
- "required": true,
- "helpMarkDown": "Where is the API definition?",
- "defaultValue": "Url",
- "options": {
- "Url": "Url",
- "Code":"Code",
- "Artifact":"Build Artifact"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "API Definition Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Url"
- },
- {
- "name": "swaggerartifact",
- "type": "string",
- "label": "API Definition Artifact",
- "required": true,
- "helpMarkDown": "API Definition Artifact. For instance $(System.DefaultWorkingDirectory)/",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Artifact"
- },
- {
- "name": "swaggercode",
- "type": "multiline",
- "label": "API Definition Body",
- "required": true,
- "helpMarkDown": "Insert the full API definition",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Code"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "DisplayName",
- "type": "string",
- "label": "API Display Name",
- "helpMarkDown": "Leave it blank to reuse the name"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": false,
- "helpMarkDown": "API version",
- "defaultValue": ""
- },
- {
- "name": "scheme",
- "type": "pickList",
- "label": "Versioning scheme",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Path",
- "options": {
- "Path": "Path",
- "Header":"Header",
- "Query":"Query String"
- },
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "version=v1"
- },
- {
- "name": "VersionHeader",
- "type": "string",
- "label": "Version Header",
- "required": true,
- "helpMarkDown": "Version Header",
- "defaultValue": "Api-Version",
- "visibleRule": "scheme = Header && version=v1"
- },
- {
- "name": "QueryParam",
- "type": "string",
- "label": "Version query parameter",
- "required": true,
- "helpMarkDown": "Version query parameter",
- "defaultValue": "api-version",
- "visibleRule": "scheme = Query && version=v1"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": false,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "multiLine",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t \n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "MicrosoftApiManagementAPIVersion",
- "type": "pickList",
- "label": "Microsoft API Version",
- "required": true,
- "helpMarkDown": "Which version of the Management API should be used?",
- "defaultValue": "2017-03-01",
- "options": {
- "2017-03-01": "2017-03-01",
- "2018-01-01":"2018-01-01",
- "2018-06-01-preview":"2018-06-01-preview"
- },
- "properties": {
- "EditableOptions": "True"
- }
- }
-
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oauth",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/authorizationServers?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oid",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/openidConnectProviders?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimversioned.ps1"
- }
- }
-}
diff --git a/apimversioned/v4/apimversioned.ps1 b/apimversioned/v4/apimversioned.ps1
deleted file mode 100644
index 0111748..0000000
--- a/apimversioned/v4/apimversioned.ps1
+++ /dev/null
@@ -1,429 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
-
-<#
-Warning: this code is provided as-is with no warranty of any kind. I do this during my free time.
-This task creates a versioned Gateway API against a backend API using the backend's swagger definition.
-Prerequisite to using this task: the API Gateway requires connectivity to the backend, so make sure these are either public, either part of a
-shared VNET
-#>
- $arm=Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $Cloud= Get-VstsInput -Name CloudEnvironment
- $Resource=Get-VstsInput -Name Resource
- $NewRevision=Get-VstsInput -Name NewRevision
- $MakeNewRevisionCurrent=Get-VstsInput -Name MakeNewRevisionCurrent
- $CurrentRevisionNotes=Get-VstsInput -Name CurrentRevisionNotes
- $currentRevision=1
- $subscriptionRequired=Get-VstsInput -Name subscriptionRequired
- $apiRevisionDescription=Get-VstsInput -Name apiRevisionDescription
- $VersionHeader= Get-VstsInput -Name VersionHeader
- $QueryParam = get-VstsInput -Name QueryParam
- $VersionScheme = Get-VstsInput -Name scheme
- $MicrosoftApiManagementAPIVersion = Get-VstsInput -Name MicrosoftApiManagementAPIVersion
- switch($VersionScheme)
- {
- "Path" {$scheme='"versioningScheme":"Segment"'}
- "Query" {$scheme='"versioningScheme":"Query","versionQueryName":"'+$($QueryParam)+'"'}
- "Header" {$scheme='"versioningScheme":"Header","versionHeaderName":"'+$($VersionHeader)+'"'}
- }
- $newapi=Get-VstsInput -Name targetapi
-
- if($newapi.startswith("/subscriptions"))
- {
- $newapi=$newapi.substring($newapi.indexOf("/apis")+6)
- }
- #this will be overwritten by the OpenAPI definition's title property
- $DisplayName=$newapi
- $v=Get-VstsInput -Name version
- $apiVersionIdentifier="$($newapi)$($v)" -replace '\.','-'
- $portal=Get-VstsInput -Name ApiPortalName
- $rg=Get-VstsInput -Name ResourceGroupName
- $SwaggerPicker = Get-VstsInput -Name SwaggerPicker
- $swaggerlocation=Get-VstsInput -Name swaggerlocation
- $swaggercode=Get-VstsInput -Name swaggercode
- $swaggerartifact = Get-VstsInput -Name swaggerartifact
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $UseProductCreatedByPreviousTask=Get-VstsInput -Name UseProductCreatedByPreviousTask
- $path = Get-VstsInput -Name pathapi
- $Authorization = Get-VstsInput -Name Authorization
- $oid = Get-VstsInput -Name oid
- $oauth = Get-VstsInput -Name oauth
- $OpenAPISpec=Get-VstsInput -Name OpenAPISpec
- $Format=Get-VstsInput -Name Format
- $AuthorizationBits='"authenticationSettings":null'
- Write-Host "Preparing API publishing in $($OpenAPISpec) format $($Format) using Azure API $($MicrosoftApiManagementAPIVersion)"
- switch($Authorization)
- {
- 'OAuth' {$AuthorizationBits='"authenticationSettings":{"oAuth2":{"authorizationServerId":"'+$oauth+'","scope":null}}'}
- 'OpenID' {$AuthorizationBits='"authenticationSettings":{"openid":{"openidProviderId":"'+$oid+'"}}'}
-
- }
- $SelectedTemplate=Get-VstsInput -Name TemplateSelector
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- if($Resource -eq $null -or $Resource -eq "")
- {
- $Resource = "https://management.azure.com/"
- }
-
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=$([System.Web.HttpUtility]::UrlEncode($Resource))"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
- try
- {
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "$($Cloud)/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($apiVersionIdentifier)?api-version=$($MicrosoftApiManagementAPIVersion)"
- #checking whether the API already exists or not. If not, a versionset must be created.
- #NotFound
- try
- {
- Write-Host "checking whether $($targeturl) exists"
- $cur=Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers|ConvertFrom-Json
- $currentversion=$cur.properties.apiVersion
- $apiexists=$true
- Write-Host "found api"
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $apiexists=$false
- }
- else
- {
- throw
- }
- }
-
- try
- {
- switch($SwaggerPicker)
- {
- "Url" {
- $cli=[System.Net.WebClient]::new()
- $swagger=$cli.DownloadString($swaggerlocation)
- $cli.Dispose()
-
- }
- "Artifact" {
- try {
- Assert-VstsPath -LiteralPath $swaggerartifact -PathType Leaf
- $swagger = Get-Content "$($swaggerartifact)" -Raw
- } catch {
- Write-Error "Invalid file location $($swaggerartifact)"
- }
- }
- "Code" {
- $swagger=$swaggercode
- }
- default {Write-Error "Invalid swagger definition"}
- }
- if($OpenAPISpec -eq "v3")
- {
- Add-Type -AssemblyName System.Web
- $swagger=$swagger.Replace("`r`n","`n")
- $swagger =[System.Web.HttpUtility]::JavaScriptStringEncode($swagger)
- }
-
- if($apiexists -eq $false)
- {
- Write-Host "Creating new API from scratch"
- #creating the api version set, the api and importing the swagger definition into it
- $version="$($newapi)versionset"
- $versionseturl="$($baseurl)/apiVersionSets/$($version)?api-version=$($MicrosoftApiManagementAPIVersion)"
- $json='{"id":"/apiVersionSets/'+$($version)+'","properties":{"name":"'+$($newapi)+'",'+$($scheme)+'}}'
- Write-Host "Creating version set using $($versionseturl) using $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $versionseturl -Body $json -ContentType "application/json" -Headers $headers -Method Put
- $apiurl="$($baseurl)/apis/$($apiVersionIdentifier)?api-version=$($MicrosoftApiManagementAPIVersion)"
- $json = '{
- "id":"/apis/'+$($newapi)+'",
- "name":"'+$($newapi)+'",
- "properties":
- { '+$AuthorizationBits+',
- "displayName":"'+$($DisplayName)+'",
- "path":"'+$($path)+'",
- "protocols":["https"],
- "subscriptionRequired":"'+$($subscriptionRequired)+'",
- "apiVersion":"'+$($v)+'",
- "apiVersionSet":{
- "id":"/apiVersionSets/'+$($version)+'",
- "name":"'+$($apiVersionIdentifier)+'",'+$($scheme)+'
- },
- "apiVersionSetId":"/apiVersionSets/'+$version+'"
- }
- }'
- $headers.Add("If-Match","*")
- Write-Host "Creating API using $($apiurl) and $($json)"
- Invoke-WebRequest -UseBasicParsing -Uri $apiurl -Body $json -ContentType "application/json" -Headers $headers -Method Put
-
- $importurl="$($baseurl)/apis/$($apiVersionIdentifier)?import=true&api-version=$($MicrosoftApiManagementAPIVersion)"
-
- Write-Host "Importing Swagger definition to API using $($importurl)"
- #to change
- if($OpenAPISpec -eq "v2")
- {
- Invoke-WebRequest -UseBasicParsing $importurl -Method Patch -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else {
- $importurl=$importurl.Substring(0,$importurl.IndexOf("api-version"))+"api-version=2018-06-01-preview"
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $openAPIBody='{"contentFormat":"'+$contentFormat+'","contentValue":"'+$swagger+'"}'
- Write-Host "OpenAPI body is $($openAPIBdoy)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/json" -Body $openAPIBody -Headers $headers
- }
-
- }
- else
- {
- $rev=1;
- #the api already exists, only a new version or revision must be created.
- $newversionurl="$($baseurl)/apis/$($apiVersionIdentifier);rev=1?api-version=$($MicrosoftApiManagementAPIVersion)"
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
-
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $newversionurl -Headers $headers
- $versionexists=$true
- }
- catch [System.Net.WebException]
- {
- if($_.Exception.Response.StatusCode -eq "NotFound")
- {
- $versionexists=$false
- }
- else
- {
- throw
- }
- }
- $headers.Add("If-Match","*")
-
- Write-Host "current version $($currentversion), version is $($v), version exists $($versionexists)"
- if($currentversion -ne $v -and $versionexists -eq $false)
- {
- #SEY
- $json='{"properties":{"name":"'+$newapi+'","displayName":"'+$DisplayName+'","sourceApiId":"/apis/'+$($newapi)+'","apiVersion":"'+$($v)+'","apiVersionSetId":"/apiversionsets/'+$newapi+'versionset"}}'
- Write-Host "Creating a new version $($newversionurl) with $($json)"
- Invoke-WebRequest -UseBasicParsing $newversionurl -Method Put -ContentType "application/json" -Body $json -Headers $headers
- }
- else
- {
- Write-Host "Getting list of revisions"
- $revisions=Invoke-WebRequest -UseBasicParsing -Uri "$($baseurl)/apis/$($apiVersionIdentifier)/revisions?api-version=$($MicrosoftApiManagementAPIVersion)" -Headers $headers|ConvertFrom-Json
-
- $revisions|% {
- $_.value|%{
- if($_.isCurrent -eq $true)
- {
- $currentRevision=$_.apiRevision
- }
- }
- }
- $revisions = $revisions.value | Sort-Object -Property "createdDateTime" -Descending
-
- Write-Host "Current revision is $($currentRevision)"
- if($NewRevision -eq $true)
- {
- $rev=([int]$revisions[0].apiRevision)+1;
- Write-Host "New revision is $($rev)"
- $revJson='{"properties":{"sourceApiId":"'+$($baseurl)+'/apis/'+$($apiVersionIdentifier)+';rev='+$($currentRevision)+'","apiRevisionDescription":"'+$($apiRevisionDescription)+'"}}'
- Write-Host "New revision body is $($revJson)"
- Invoke-WebRequest -ContentType "application/json" -UseBasicParsing -Uri "$($baseurl)/apis/$($apiVersionIdentifier);rev=$($rev)?api-version=$($MicrosoftApiManagementAPIVersion)" -Headers $headers -Method Put -Body $revJson
- Write-Host "Revision $($rev) created"
- if($MakeNewRevisionCurrent -eq $true)
- {
- Write-Host "Making new revision current"
- $releaseId=[guid]::NewGuid()
- $currentRevReleaseBody='{"properties":{"apiId":"/apis/'+$($apiVersionIdentifier)+';rev='+$($rev)+'","notes":"'+$CurrentRevisionNotes+'"}}'
- $currentRevisionUrl="$($baseurl)/apis/$($apiVersionIdentifier);rev=$($rev)/releases/$($releaseId)?api-version=$($MicrosoftApiManagementAPIVersion)"
- Write-Host $currentRevisionUrl
- Write-Host $currentRevReleaseBody
- $resp=Invoke-WebRequest -ContentType "application/json" -UseBasicParsing -Uri $currentRevisionUrl -Headers $headers -Method Put -Body $currentRevReleaseBody
- Write-Host $resp
- }
- }
- else
- {
- $rev=$currentRevision;
- }
- }
- $authurl = "$($baseurl)/apis/$($apiVersionIdentifier);rev=$($rev)?api-version=$($MicrosoftApiManagementAPIVersion)"
- $importurl="$($baseurl)/apis/$($apiVersionIdentifier);rev=$($rev)?import=true&api-version=$($MicrosoftApiManagementAPIVersion)"
-
- Write-Host "applying authorization"
-
- $json='{"name":"'+$apiVersionIdentifier+'","properties":{'+$AuthorizationBits+',"ApiVersionSetId":"/apiVersionSets/'+$($newapi)+'versionset","apiVersion":"'+$v+'"}}'
- Write-Host "Authorization json $($json)"
- Write-Host "endpoint is $($authurl) headers are $($headers)"
- Invoke-WebRequest -UseBasicParsing -Uri $authurl -Headers $headers -Method "PATCH" -ContentType "application/json" -Body $json
- Write-Host "applied authorization"
- #reapplying swagger
-
- Write-Host "Importing swagger $($importurl) spec is $($OpenAPISpec) format is $($Format)"
- Write-Host "Applying $($swagger)"
- if($OpenAPISpec -eq "v2")
- {
- Invoke-WebRequest -UseBasicParsing $importurl -Method Patch -ContentType "application/vnd.swagger.doc+json" -Body $swagger -Headers $headers
- }
- else {
- $importurl=$importurl.Substring(0,$importurl.IndexOf("api-version"))+"api-version=2018-06-01-preview"
- if($Format -eq 'json')
- {
- $contentFormat="openapi+json"
- }else{
- $contentFormat="openapi"
- }
- $openAPIBody='{"contentFormat":"'+$contentFormat+'","contentValue":"'+$swagger+'"}'
- Write-Host "API Body is $($openAPIBody)"
- Invoke-WebRequest -UseBasicParsing $importurl -Method Put -ContentType "application/json" -Body $openAPIBody -Headers $headers
-
- }
-
- }
-
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($apiVersionIdentifier)?api-version=$($MicrosoftApiManagementAPIVersion)"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($apiVersionIdentifier);rev=$($rev)/policies/policy?api-version=$($MicrosoftApiManagementAPIVersion)"
- $JsonPolicies = "{
- `"properties`": {
- `"format`":`"rawxml`",
- `"value`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
diff --git a/apimversioned/v4/icon.png b/apimversioned/v4/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimversioned/v4/icon.png and /dev/null differ
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimversioned/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/module.json b/apimversioned/v4/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimversioned/v4/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimversioned/v4/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Minimatch.dll b/apimversioned/v4/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimversioned/v4/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimversioned/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimversioned/v4/ps_modules/VstsTaskSdk/lib.json b/apimversioned/v4/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimversioned/v4/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimversioned/v4/task.json b/apimversioned/v4/task.json
deleted file mode 100644
index db5904a..0000000
--- a/apimversioned/v4/task.json
+++ /dev/null
@@ -1,452 +0,0 @@
-{
- "id": "caee5262-b7ce-48c9-b5f7-70c586148ff8",
- "name": "apimversioned",
- "friendlyName": "API Management - Create or Update Versioned API",
- "description": "API Management - Create or Update Versioned API",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "4",
- "Minor": "1",
- "Patch": "2"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
- },
- {
- "name":"CloudEnvironment",
- "type":"string",
- "label":"Azure Cloud",
- "defaultValue":"https://login.windows.net/",
- "required":true,
- "helpMarkDown": "Keep the default if you're not using a Sovereign Cloud",
- "options": {
- "China": "https://login.chinacloudapi.cn",
- "US Gov.":"https://login.microsoftonline.us",
- "Germany":"https://login.microsoftonline.de"
- }
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "OpenAPISpec",
- "type": "pickList",
- "label": "OpenAPI Version",
- "required": true,
- "helpMarkDown": "Target Open API version.",
- "defaultValue": "v2",
- "options": {
- "v2": "v2",
- "v3":"v3"
- }
- },
- {
- "name": "Format",
- "type": "pickList",
- "label": "API definition format",
- "required": true,
- "helpMarkDown": "API definition format",
- "defaultValue": "json",
- "options": {
- "json": "json",
- "yaml":"yaml"
- },
- "visibleRule": "OpenAPISpec=v3"
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "Authorization",
- "type": "pickList",
- "label": "Authorization",
- "required": true,
- "helpMarkDown": "Enable Authorization for the developer portal",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "OAuth":"OAuth",
- "OpenID":"OpenID Connect"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "oauth",
- "type": "pickList",
- "label": "Authorization server",
- "required": false,
- "helpMarkDown": "Authorization server to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OAuth"
- },
- {
- "name": "oid",
- "type": "pickList",
- "label": "OpenID Connect",
- "required": false,
- "helpMarkDown": "OpenID provider to associate to the API",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "Authorization=OpenID"
- },
- {
- "name": "SwaggerPicker",
- "type": "pickList",
- "label": "Definition location",
- "required": true,
- "helpMarkDown": "Where is the API definition?",
- "defaultValue": "Url",
- "options": {
- "Url": "Url",
- "Code":"Code",
- "Artifact":"Build Artifact"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "swaggerlocation",
- "type": "string",
- "label": "API Definition Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Url"
- },
- {
- "name": "swaggerartifact",
- "type": "string",
- "label": "API Definition Artifact",
- "required": true,
- "helpMarkDown": "API Definition Artifact. For instance $(System.DefaultWorkingDirectory)/",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Artifact"
- },
- {
- "name": "swaggercode",
- "type": "multiline",
- "label": "API Definition Body",
- "required": true,
- "helpMarkDown": "Insert the full API definition",
- "defaultValue": "",
- "visibleRule": "SwaggerPicker=Code"
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "version",
- "type": "string",
- "label": "API Version",
- "required": false,
- "helpMarkDown": "API version",
- "defaultValue": ""
- },
- {
- "name": "subscriptionRequired",
- "type": "boolean",
- "label": "Subscription Required",
- "helpMarkDown": "Subscription key is required to access this API",
- "defaultValue":true
- },
- {
- "name": "NewRevision",
- "type": "boolean",
- "label": "Create a new revision",
- "helpMarkDown": "When set to false, overwrite the current revision if no new version specified, else create a new one",
- "defaultValue":true
- },
- {
- "name": "MakeNewRevisionCurrent",
- "type": "boolean",
- "label": "Make the new revision current",
- "helpMarkDown": "When set to false, overwrite the current revision if no new version specified, else create a new one",
- "defaultValue":false,
- "visibleRule": "NewRevision=true"
- },
- {
- "name": "CurrentRevisionNotes",
- "type": "string",
- "label": "Notes to push to Change Feed",
- "required": false,
- "helpMarkDown": "Release notes of the new revision",
- "defaultValue": "N/A",
- "visibleRule": "MakeNewRevisionCurrent=true"
- },
- {
- "name": "apiRevisionDescription",
- "type": "string",
- "label": "API revision description",
- "required": true,
- "helpMarkDown": "Release notes of the new revision",
- "defaultValue": "N/A",
- "visibleRule": "NewRevision=true"
- },
- {
- "name": "scheme",
- "type": "pickList",
- "label": "Versioning scheme",
- "required": true,
- "helpMarkDown": "How should the API version be transmitted by consumers",
- "defaultValue": "Path",
- "options": {
- "Path": "Path",
- "Header":"Header",
- "Query":"Query String"
- },
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "version=v1"
- },
- {
- "name": "VersionHeader",
- "type": "string",
- "label": "Version Header",
- "required": true,
- "helpMarkDown": "Version Header",
- "defaultValue": "Api-Version",
- "visibleRule": "scheme = Header && version=v1"
- },
- {
- "name": "QueryParam",
- "type": "string",
- "label": "Version query parameter",
- "required": true,
- "helpMarkDown": "Version query parameter",
- "defaultValue": "api-version",
- "visibleRule": "scheme = Query && version=v1"
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": false,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache Lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "multiLine",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\t\n\t \n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "MicrosoftApiManagementAPIVersion",
- "type": "pickList",
- "label": "Microsoft API Version",
- "required": true,
- "helpMarkDown": "Which version of the Management API should be used?",
- "defaultValue": "2019-01-01",
- "options": {
- "2019-01-01":"2019-01-01"
- },
- "properties": {
- "EditableOptions": "True"
- }
- }
-
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oauth",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/authorizationServers?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- },
- {
- "target": "oid",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/openidConnectProviders?api-version=2018-01-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimversioned.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimversioned/v5/task.json b/apimversioned/v5/task.json
index 62cb86b..b7e38ae 100644
--- a/apimversioned/v5/task.json
+++ b/apimversioned/v5/task.json
@@ -1,5 +1,5 @@
{
- "id": "caee5262-b7ce-48c9-b5f7-70c586148ff8",
+ "id": "3b6d8328-cfd2-4a3d-8a13-a02271f20e0c",
"name": "apimversioned",
"friendlyName": "API Management - Create or Update Versioned API",
"description": "API Management - Create or Update Versioned API",
diff --git a/apimwsdl/v1/apimwsdl.ps1 b/apimwsdl/v1/apimwsdl.ps1
deleted file mode 100644
index f1cf508..0000000
--- a/apimwsdl/v1/apimwsdl.ps1
+++ /dev/null
@@ -1,178 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
- Import-Module $PSScriptRoot\ps_modules\Share\functions.psm1
-
- $arm = Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi= Get-Slug $(Get-VstsInput -Name targetapi)
- $description=Get-VstsInput -Name Description
- $path = Get-VstsInput -Name pathapi
- $soapApiType = Get-VstsInput -Name soapApiType
- $portal = Get-VstsInput -Name ApiPortalName
- $rg = Get-VstsInput -Name ResourceGroupName
- $wsdllocation = Get-VstsInput -Name wsdllocation
- $wsdlServiceName = Get-VstsInput -Name wsdlServiceName
- $wsdlEndpointName = Get-VstsInput -Name wsdlEndpointName
- $product = Get-Slug $(Get-VstsInput -Name product1)
- $UseProductCreatedByPreviousTask = Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate = Get-VstsInput -Name TemplateSelector
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json = '{
- "properties": {
- "contentFormat": "wsdl-link",
- "wsdlSelector" : {
- "wsdlEndpointName": "' + $($wsdlEndpointName) + '",
- "wsdlServiceName": "' + $($wsdlServiceName) + '"
- },
- "apiType": "'+$($soapApiType)+'",
- "contentValue": "'+$($wsdllocation)+'",
- "displayName": "'+$($newapi)+'",
- "description": "'+$description+'",
- "path": "'+$($path)+'",
- "protocols": ["https"]
- }
- }'
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=2017-03-01"
- Write-Host "Creating or updating API $($targeturl)"
-
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- $product = $env:NewUpdatedProduct
- if($product -eq $null -or $product -eq "")
- {
- throw "There was no product created by a previous task"
- }
- }
-
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=2017-03-01"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- }
-
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=2017-03-01"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/icon.png b/apimwsdl/v1/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimwsdl/v1/icon.png and /dev/null differ
diff --git a/apimwsdl/v1/ps_modules/Share/functions.psm1 b/apimwsdl/v1/ps_modules/Share/functions.psm1
deleted file mode 100644
index b7e205d..0000000
--- a/apimwsdl/v1/ps_modules/Share/functions.psm1
+++ /dev/null
@@ -1,11 +0,0 @@
-function Get-Slug {
- param([String] $name)
- $slug = $name.ToLower()
- $slug = $slug -replace "[^a-z0-9\s-]", ""
- $slug = $($slug -replace "[\s-]+", " ").Trim()
- $slug = $slug.Substring(0, $slug.Length).Trim()
- $slug = $slug -replace "\s", "-"
- return $slug
-}
-
-Export-ModuleMember -function 'Get-*'
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/module.json b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimwsdl/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimwsdl/v1/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Minimatch.dll b/apimwsdl/v1/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimwsdl/v1/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimwsdl/v1/ps_modules/VstsTaskSdk/lib.json b/apimwsdl/v1/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimwsdl/v1/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimwsdl/v1/task.json b/apimwsdl/v1/task.json
deleted file mode 100644
index 800952e..0000000
--- a/apimwsdl/v1/task.json
+++ /dev/null
@@ -1,268 +0,0 @@
-{
- "id": "9bfd810a-5e2b-4871-95d8-ae6e677d4224",
- "name": "apimwsdl",
- "friendlyName": "API Management - Create or Update API from WSDL",
- "description": "API Management - Create or update API from WSDL",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API from WSDL",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "1",
- "Minor": "0",
- "Patch": "2"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API from WSDL $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "pickList",
- "label": "Product",
- "required": false,
- "helpMarkDown": "Product you want to add the API to.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "soapApiType",
- "type": "pickList",
- "label": "Type of Api to create",
- "required": true,
- "helpMarkDown": "Type of Api to create.",
- "defaultValue": "soap",
- "options": {
- "soap":"SOAP pass-through API",
- "http": "SOAP to REST API"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "wsdllocation",
- "type": "string",
- "label": "WSDL Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": ""
- },
- {
- "name": "wsdlServiceName",
- "type": "string",
- "label": "Service Name",
- "required": true,
- "helpMarkDown": "Name of the service as described in the WSDL",
- "defaultValue": ""
- },
- {
- "name": "wsdlEndpointName",
- "type": "string",
- "label": "Service Endpoint",
- "required": true,
- "helpMarkDown": "Name of endpoint(port) to import from WSDL.",
- "defaultValue": ""
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "Description",
- "type": "multiLine",
- "label": "Description",
- "helpMarkDown": "Description appearing to subscribers",
- "required": true
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "multiLine",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimwsdl.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/apimwsdl.ps1 b/apimwsdl/v2/apimwsdl.ps1
deleted file mode 100644
index 41494aa..0000000
--- a/apimwsdl/v2/apimwsdl.ps1
+++ /dev/null
@@ -1,189 +0,0 @@
-[CmdletBinding()]
-param()
-Trace-VstsEnteringInvocation $MyInvocation
-try {
- Import-Module $PSScriptRoot\ps_modules\Share\functions.psm1
-
- $arm = Get-VstsInput -Name ConnectedServiceNameARM
- $Endpoint = Get-VstsEndpoint -Name $arm -Require
- $newapi= Get-Slug $(Get-VstsInput -Name targetapi)
- $description=Get-VstsInput -Name Description
- $path = Get-VstsInput -Name pathapi
- $soapApiType = Get-VstsInput -Name soapApiType
- $portal = Get-VstsInput -Name ApiPortalName
- $rg = Get-VstsInput -Name ResourceGroupName
- $MicrosoftApiManagementAPIVersion = Get-VstsInput -Name MicrosoftApiManagementAPIVersion
- $wsdllocation = Get-VstsInput -Name wsdllocation
- $wsdlServiceName = Get-VstsInput -Name wsdlServiceName
- $wsdlEndpointName = Get-VstsInput -Name wsdlEndpointName
- $products = $(Get-VstsInput -Name product1).Split([Environment]::NewLine)
- $UseProductCreatedByPreviousTask = Get-VstsInput -Name UseProductCreatedByPreviousTask
- $SelectedTemplate = Get-VstsInput -Name TemplateSelector
-
- if($SelectedTemplate -eq "CacheLookup")
- {
- $PolicyContent = Get-VstsInput -Name CacheLookup
- }
- if($SelectedTemplate -eq "CORS")
- {
- $PolicyContent = Get-VstsInput -Name CORS
- }
- if($SelectedTemplate -eq "None")
- {
- $PolicyContent = Get-VstsInput -Name None
- }
- if($SelectedTemplate -eq "Basic")
- {
- $PolicyContent = Get-VstsInput -Name Basic
- }
- if($SelectedTemplate -eq "JWT")
- {
- $PolicyContent = Get-VstsInput -Name JWT
- }
- if($SelectedTemplate -eq "IP")
- {
- $PolicyContent = Get-VstsInput -Name IP
- }
- if($SelectedTemplate -eq "RateByKey")
- {
- $PolicyContent = Get-VstsInput -Name RateByKey
- }
- if($SelectedTemplate -eq "QuotaByKey")
- {
- $PolicyContent = Get-VstsInput -Name QuotaByKey
- }
- if($SelectedTemplate -eq "HeaderCheck")
- {
- $PolicyContent = Get-VstsInput -Name HeaderCheck
- }
- if($SelectedTemplate -eq "Custom")
- {
- $PolicyContent = Get-VstsInput -Name Custom
- }
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- $PolicyContent = $PolicyContent.replace("`"","`\`"")
- }
-
- $client=$Endpoint.Auth.Parameters.ServicePrincipalId
- $secret=[System.Web.HttpUtility]::UrlEncode($Endpoint.Auth.Parameters.ServicePrincipalKey)
- $tenant=$Endpoint.Auth.Parameters.TenantId
- $body="resource=https%3A%2F%2Fmanagement.azure.com%2F"+
- "&client_id=$($client)"+
- "&grant_type=client_credentials"+
- "&client_secret=$($secret)"
-
- try
- {
- #getting ARM token
- $resp=Invoke-WebRequest -UseBasicParsing -Uri "https://login.windows.net/$($tenant)/oauth2/token" `
- -Method POST `
- -Body $body| ConvertFrom-Json
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- write-host $er.error.details
- throw
- }
-
- $headers = @{
- Authorization = "Bearer $($resp.access_token)"
- }
- $json = '{
- "properties": {
- "contentFormat": "wsdl-link",
- "wsdlSelector" : {
- "wsdlEndpointName": "' + $($wsdlEndpointName) + '",
- "wsdlServiceName": "' + $($wsdlServiceName) + '"
- },
- "apiType": "'+$($soapApiType)+'",
- "contentValue": "'+$($wsdllocation)+'",
- "displayName": "'+$($newapi)+'",
- "description": "'+$description+'",
- "path": "'+$($path)+'",
- "protocols": ["https"]
- }
- }'
-
- write-host $json
- $baseurl="$($Endpoint.Url)subscriptions/$($Endpoint.Data.SubscriptionId)/resourceGroups/$($rg)/providers/Microsoft.ApiManagement/service/$($portal)"
- $targeturl="$($baseurl)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
- Write-Host "Creating or updating API $($targeturl)"
-
- try
- {
- Invoke-WebRequest -UseBasicParsing -Uri $targeturl -Headers $headers -Body $json -Method Put -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
-
- if($UseProductCreatedByPreviousTask -eq $true)
- {
- if ($null -eq $env:NewUpdatedProduct)
- {
- throw "There was no product created by a previous task"
- }
-
- $products = $env:NewUpdatedProduct.Split(";")
-
- if ($products.Length -le 0)
- {
- $products = $env:NewUpdatedProduct
- }
-
- Write-Host "Number of products created by a previous task(s): $($products.Length)"
- }
-
- foreach ($product in $products)
- {
- if($product -ne $null -and $product -ne "")
- {
- $productapiurl= "$($baseurl)/products/$($product)/apis/$($newapi)?api-version=$($MicrosoftApiManagementAPIVersion)"
-
- try
- {
- Write-Host "Linking API to product $($productapiurl)"
- Invoke-WebRequest -UseBasicParsing -Uri $productapiurl -Headers $headers -Method Put
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
- }
-
- #Policy content should never be null or empty. The 'none' policy will always apply if nothing is specified.
- if($PolicyContent -ne $null -and $PolicyContent -ne "")
- {
- try
- {
- $policyapiurl= "$($baseurl)/apis/$($newapi)/policies/policy?api-version=$($MicrosoftApiManagementAPIVersion)"
- $JsonPolicies = "{
- `"properties`": {
- `"policyContent`":`""+$PolicyContent+"`"
- }
- }"
- Write-Host "Linking policy to API USING $($policyapiurl)"
- Write-Host $JsonPolicies
- Invoke-WebRequest -UseBasicParsing -Uri $policyapiurl -Headers $headers -Method Put -Body $JsonPolicies -ContentType "application/json"
- }
- catch [System.Net.WebException]
- {
- $er=$_.ErrorDetails.Message.ToString()|ConvertFrom-Json
- Write-Host $er.error.details
- throw
- }
- }
-
- Write-Host $rep
-
-} finally {
- Trace-VstsLeavingInvocation $MyInvocation
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/icon.png b/apimwsdl/v2/icon.png
deleted file mode 100644
index 3196e54..0000000
Binary files a/apimwsdl/v2/icon.png and /dev/null differ
diff --git a/apimwsdl/v2/ps_modules/Share/functions.psm1 b/apimwsdl/v2/ps_modules/Share/functions.psm1
deleted file mode 100644
index b7e205d..0000000
--- a/apimwsdl/v2/ps_modules/Share/functions.psm1
+++ /dev/null
@@ -1,11 +0,0 @@
-function Get-Slug {
- param([String] $name)
- $slug = $name.ToLower()
- $slug = $slug -replace "[^a-z0-9\s-]", ""
- $slug = $($slug -replace "[\s-]+", " ").Trim()
- $slug = $slug.Substring(0, $slug.Length).Trim()
- $slug = $slug -replace "\s", "-"
- return $slug
-}
-
-Export-ModuleMember -function 'Get-*'
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
deleted file mode 100644
index a5ae786..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/ImportFunctions.ps1
+++ /dev/null
@@ -1,223 +0,0 @@
-function Import-AzureModule {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ValidateSet('Azure', 'AzureRM')]
- [string[]] $PreferredModule,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- Write-Verbose "Env:PSModulePath: '$env:PSMODULEPATH'"
- if ($PreferredModule -contains 'Azure' -and $PreferredModule -contains 'AzureRM') {
- # Attempt to import Azure and AzureRM.
- $azure = (Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion)
- $azureRM = (Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -or (Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion)
- if (!$azure -and !$azureRM) {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } elseif ($PreferredModule -contains 'Azure') {
- # Attempt to import Azure but fallback to AzureRM.
- if (!(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- } else {
- # Attempt to import AzureRM but fallback to Azure.
- if (!(Import-FromModulePath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$false -azurePsVersion $azurePsVersion) -and
- !(Import-FromModulePath -Classic:$true -azurePsVersion $azurePsVersion) -and
- !(Import-FromSdkPath -Classic:$true -azurePsVersion $azurePsVersion))
- {
- Discover-AvailableAzureModules
- if ($azurePsVersion) {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList $azurePsVersion)
- } else {
- throw (Get-VstsLocString -Key AZ_ModuleNotFound -ArgumentList "Any version")
- }
- }
- }
-
- # Validate the Classic version.
- $minimumVersion = [version]'0.8.10.1'
- if ($script:azureModule -and $script:azureModule.Version -lt $minimumVersion) {
- throw (Get-VstsLocString -Key AZ_RequiresMinVersion0 -ArgumentList $minimumVersion)
- }
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromModulePath {
- [CmdletBinding()]
- param(
- [switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Determine which module to look for.
- if ($Classic) {
- $name = "Azure"
- } else {
- $name = "AzureRM"
- }
-
- # Attempt to resolve the module.
- Write-Verbose "Attempting to find the module '$name' from the module path."
- if ($azurePsVersion) {
- $module = Get-Module -Name $name -ListAvailable | Where-Object {$_.Version -eq $azurePsVersion} | Select-Object -First 1
- if (!$module) {
- Write-Verbose "No module found with name: $name, version: $azurePsVersion"
- return $false
- }
- }
- else {
- $module = Get-Module -Name $name -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
- $sdkVersion = Get-SdkVersion
- if ((!$module) -or ($sdkVersion -and ($module.Version -lt [version]$sdkVersion))) {
- return $false
- }
- }
-
- # Import the module.
- Write-Host "##[command]Import-Module -Name $($module.Path) -Global"
- $module = Import-Module -Name $module.Path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
-
- if ($Classic) {
- # Store the imported Azure module.
- $script:azureModule = $module
- } else {
- # The AzureRM module was imported.
- # Validate the AzureRM.profile module can be found.
- $profileModule = (Get-Module -Name AzureRM).NestedModules | Where-Object { $_.Name.toLower() -eq "azurerm.profile" }
- if (!$profileModule) {
- throw (Get-VstsLocString -Key AZ_AzureRMProfileModuleNotFound)
- }
- # Import and then store the AzureRM.profile module.
- Write-Host "##[command]Import-Module -Name $($profileModule.Path) -Global"
- $script:azureRMProfileModule = Import-Module -Name $profileModule.Path -Global -PassThru
- Write-Verbose "Imported module version: $($script:azureRMProfileModule.Version)"
- }
-
- return $true
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-FromSdkPath {
- [CmdletBinding()]
- param([switch] $Classic,
- [string] $azurePsVersion)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- if ($Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- foreach ($programFiles in @(${env:ProgramFiles(x86)}, $env:ProgramFiles)) {
- if (!$programFiles) {
- continue
- }
-
- $path = [System.IO.Path]::Combine($programFiles, $partialPath)
- Write-Verbose "Checking if path exists: $path"
- if (Test-Path -LiteralPath $path -PathType Leaf) {
- if ($azurePsVersion -and (-not ($(Get-SdkVersion) -eq $azurePsVersion))) {
- continue
- }
- # Import the module.
- Write-Host "##[command]Import-Module -Name $path -Global"
- $module = Import-Module -Name $path -Global -PassThru
- Write-Verbose "Imported module version: $($module.Version)"
- # Store the imported module.
- if ($Classic) {
- $script:azureModule = $module
- } else {
- # Import all the possible AzureRM submodules
- Import-AzureRmSubmodulesFromSdkPath -path $path -programFiles $programFiles
- $script:azureRMProfileModule = $module
- }
- return $true
- }
- }
-
- return $false
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Get-SdkVersion {
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- $regKey = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
- $installedApplications = Get-ItemProperty -Path $regKey
- $SdkVersion = ($installedApplications | Where-Object { $_.DisplayName -and $_.DisplayName.toLower().Contains("microsoft azure powershell") } | Select-Object -First 1).DisplayVersion
- Write-Verbose "The installed sdk version is: $SdkVersion"
- return $SdkVersion
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function Import-AzureRmSubmodulesFromSdkPath {
- [CmdletBinding()]
- param([string] $path,
- [string] $programFiles)
- try {
- # Azure.Storage submodule needs to be imported first
- $azureStorageModulePath = [System.IO.Path]::Combine($programFiles, "Microsoft SDKs\Azure\PowerShell\Storage\Azure.Storage\Azure.Storage.psd1")
- Write-Host "##[command]Import-Module -Name $azureStorageModulePath -Global"
- $azureStorageModule = Import-Module -Name $azureStorageModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureStorageModule.Version)"
- }
- catch {
- Write-Verbose $("The import of the Azure Storage module: \'$azureStorageModulePath\' failed with the error: $($_.Exception.Message)")
- }
-
- # Try to import all the AzureRM submodules
- $azureRmNestedModulesDirectory = Split-Path -Parent (Split-Path -Parent $path)
- $azureRmNestedModules = Get-ChildItem -Path $azureRmNestedModulesDirectory -Directory
- foreach ($azureRmNestedModule in $azureRmNestedModules) {
- #AzureRM.Profile module has already been imported
- if ($azureRmNestedModule.Name.toLower() -eq "azurerm.profile") {
- continue;
- }
- $azureRmNestedModulePath = [System.IO.Path]::Combine($azureRmNestedModule.FullName, $azureRmNestedModule.Name + ".psd1")
- try {
- Write-Verbose "##[command]Import-Module -Name $azureRmNestedModulePath -Global"
- $azureRmSubmodule = Import-Module -Name $azureRmNestedModulePath -Global -PassThru
- Write-Verbose "Imported module version: $($azureRmSubmodule.Version)"
- }
- catch {
- Write-Verbose $("The import of the AzureRM submodule \'$azureRmNestedModulePath\' failed with the error: $($_.Exception.Message)")
- }
- }
-}
-
-function Discover-AvailableAzureModules {
- $env:PSModulePath = $env:SystemDrive + "\Modules;" + $env:PSModulePath
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "Azure")
- Get-Module -Name Azure -ListAvailable | Select-Object Name,Version | ft
- Write-Host $(Get-VstsLocString -Key AZ_AvailableModules -ArgumentList "AzureRM")
- Get-Module -Name AzureRM -ListAvailable | Select-Object Name,Version | ft
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
deleted file mode 100644
index fa7bc8a..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/InitializeFunctions.ps1
+++ /dev/null
@@ -1,360 +0,0 @@
-function Add-Certificate {
- [CmdletBinding()]
- param([Parameter(Mandatory=$true)]$Endpoint)
-
- # Add the certificate to the cert store.
- $bytes = [System.Convert]::FromBase64String($Endpoint.Auth.Parameters.Certificate)
- $certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
- $certificate.Import($bytes)
- $store = New-Object System.Security.Cryptography.X509Certificates.X509Store(
- ([System.Security.Cryptography.X509Certificates.StoreName]::My),
- ([System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser))
- $store.Open(([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite))
- $store.Add($certificate)
- $store.Close()
- return $certificate
-}
-
-function Format-Splat {
- [CmdletBinding()]
- param([Parameter(Mandatory = $true)][hashtable]$Hashtable)
-
- # Collect the parameters (names and values) in an array.
- $parameters = foreach ($key in $Hashtable.Keys) {
- $value = $Hashtable[$key]
- # If the value is a bool, format the parameter as a switch (ending with ':').
- if ($value -is [bool]) { "-$($key):" } else { "-$key" }
- $value
- }
-
- $OFS = " "
- "$parameters" # String join the array.
-}
-
-function Initialize-AzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- $Endpoint,
- [Parameter(Mandatory=$false)]
- [string]$StorageAccount)
-
- #Set UserAgent for Azure Calls
- Set-UserAgent
-
- $environmentName = "AzureCloud"
- if($Endpoint.Data.Environment) {
- $environmentName = $Endpoint.Data.Environment
- if($environmentName -eq "AzureStack")
- {
- Add-AzureStackAzureRmEnvironment -endpoint $Endpoint -name "AzureStack"
- }
- }
-
- if ($Endpoint.Auth.Scheme -eq 'Certificate') {
- # Certificate is only supported for the Azure module.
- if (!$script:azureModule) {
- throw (Get-VstsLocString -Key AZ_CertificateAuthNotSupported)
- }
-
- # Add the certificate to the cert store.
- $certificate = Add-Certificate -Endpoint $Endpoint
-
- # Setup the additional parameters.
- $additional = @{ }
- if ($StorageAccount) {
- $additional['CurrentStorageAccountName'] = $StorageAccount
- }
-
- # Set the subscription.
- Write-Host "##[command]Set-AzureSubscription -SubscriptionName $($Endpoint.Data.SubscriptionName) -SubscriptionId $($Endpoint.Data.SubscriptionId) -Certificate ******** -Environment $environmentName $(Format-Splat $additional)"
- Set-AzureSubscription -SubscriptionName $Endpoint.Data.SubscriptionName -SubscriptionId $Endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName @additional
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($Endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.UserName,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.Password -AsPlainText -Force))
-
- # Add account (Azure).
- if ($script:azureModule) {
- try {
- Write-Host "##[command]Add-AzureAccount -Credential $psCredential"
- $null = Add-AzureAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Add account (AzureRM).
- if ($script:azureRMProfileModule) {
- try {
- Write-Host "##[command]Add-AzureRMAccount -Credential $psCredential"
- $null = Add-AzureRMAccount -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_CredentialsError), $_.Exception))
- }
- }
-
- # Select subscription (Azure).
- if ($script:azureModule) {
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- }
-
- # Select subscription (AzureRM).
- if ($script:azureRMProfileModule) {
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId
- }
- } elseif ($Endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $psCredential = New-Object System.Management.Automation.PSCredential(
- $Endpoint.Auth.Parameters.ServicePrincipalId,
- (ConvertTo-SecureString $Endpoint.Auth.Parameters.ServicePrincipalKey -AsPlainText -Force))
- if ($script:azureModule -and $script:azureModule.Version -lt ([version]'0.9.9')) {
- # Service principals arent supported from 0.9.9 and greater in the Azure module.
- try {
- Write-Host "##[command]Add-AzureAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential"
- $null = Add-AzureAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -StorageAccount $StorageAccount
- } elseif ($script:azureModule) {
- # Throw if >=0.9.9 Azure.
- throw (Get-VstsLocString -Key "AZ_ServicePrincipalAuthNotSupportedAzureVersion0" -ArgumentList $script:azureModule.Version)
- } else {
- # Else, this is AzureRM.
- try {
- if(CmdletHasMember -cmdlet "Add-AzureRMAccount" -memberName "EnvironmentName")
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -EnvironmentName $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -EnvironmentName $environmentName
- }
- else
- {
- Write-Host "##[command]Add-AzureRMAccount -ServicePrincipal -Tenant $($Endpoint.Auth.Parameters.TenantId) -Credential $psCredential -Environment $environmentName"
- $null = Add-AzureRMAccount -ServicePrincipal -Tenant $Endpoint.Auth.Parameters.TenantId -Credential $psCredential -Environment $environmentName
- }
- } catch {
- # Provide an additional, custom, credentials-related error message.
- Write-VstsTaskError -Message $_.Exception.Message
- throw (New-Object System.Exception((Get-VstsLocString -Key AZ_ServicePrincipalError), $_.Exception))
- }
-
- Set-CurrentAzureRMSubscription -SubscriptionId $Endpoint.Data.SubscriptionId -TenantId $Endpoint.Auth.Parameters.TenantId
- }
- } else {
- throw (Get-VstsLocString -Key AZ_UnsupportedAuthScheme0 -ArgumentList $Endpoint.Auth.Scheme)
- }
-}
-
-function Set-CurrentAzureSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$StorageAccount)
-
- $additional = @{ }
- if ($script:azureModule.Version -lt ([version]'0.8.15')) {
- $additional['Default'] = $true # The Default switch is required prior to 0.8.15.
- }
-
- Write-Host "##[command]Select-AzureSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureSubscription -SubscriptionId $SubscriptionId @additional
- if ($StorageAccount) {
- Write-Host "##[command]Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount"
- Set-AzureSubscription -SubscriptionId $SubscriptionId -CurrentStorageAccountName $StorageAccount
- }
-}
-
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-
-function Set-UserAgent {
- [CmdletBinding()]
- param()
-
- $userAgent = Get-VstsTaskVariable -Name AZURE_HTTP_USER_AGENT
- if ($userAgent) {
- Set-UserAgent_Core -UserAgent $userAgent
- }
-}
-
-function Set-UserAgent_Core {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$UserAgent)
-
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- [Microsoft.Azure.Common.Authentication.AzureSession]::ClientFactory.AddUserAgent($UserAgent)
- } catch {
- Write-Verbose "Set-UserAgent failed with exception message: $_.Exception.Message"
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-function CmdletHasMember {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$cmdlet,
- [Parameter(Mandatory=$true)]
- [string]$memberName)
- try{
- $hasMember = (gcm $cmdlet).Parameters.Keys.Contains($memberName)
- return $hasMember
- }
- catch
- {
- return false;
- }
-}
-
-<#
- Adds Azure Stack environment to use with AzureRM command-lets when targeting Azure Stack
-#>
-function Add-AzureStackAzureRmEnvironment {
- param (
- [Parameter(mandatory=$true, HelpMessage="The Admin ARM endpoint of the Azure Stack Environment")]
- $Endpoint,
- [parameter(mandatory=$true, HelpMessage="Azure Stack environment name for use with AzureRM commandlets")]
- [string] $Name
- )
-
- $EndpointURI = $Endpoint.Url.TrimEnd("/")
-
- $Domain = ""
- try {
- $uriendpoint = [System.Uri] $EndpointURI
- $i = $EndpointURI.IndexOf('.')
- $Domain = ($EndpointURI.Remove(0,$i+1)).TrimEnd('/')
- }
- catch {
- Write-Error (Get-VstsLocString -Key AZ_InvalidARMEndpoint)
- }
-
- $ResourceManagerEndpoint = $EndpointURI
- $stackdomain = $Domain
-
- $AzureKeyVaultDnsSuffix="vault.$($stackdomain)".ToLowerInvariant()
- $AzureKeyVaultServiceEndpointResourceId= $("https://vault.$stackdomain".ToLowerInvariant())
- $StorageEndpointSuffix = ($stackdomain).ToLowerInvariant()
-
- # Check if endpoint data contains required data.
- if($Endpoint.data.GraphUrl -eq $null)
- {
- $azureStackEndpointUri = $EndpointURI.ToString() + "/metadata/endpoints?api-version=2015-01-01"
- $proxyUri = Get-ProxyUri $azureStackEndpointUri
-
- Write-Verbose "Retrieving endpoints from the $ResourceManagerEndpoint"
- if ($proxyUri -eq $null)
- {
- Write-Verbose "No proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -ErrorAction Stop
- }
- else
- {
- Write-Verbose "Using Proxy settings"
- $endpointData = Invoke-RestMethod -Uri $azureStackEndpointUri -Method Get -Proxy $proxyUri -ErrorAction Stop
- }
-
- if ($endpointData)
- {
- $authenticationData = $endpointData.authentication;
- if ($authenticationData)
- {
- $loginEndpoint = $authenticationData.loginEndpoint
- if($loginEndpoint)
- {
- $aadAuthorityEndpoint = $loginEndpoint
- $activeDirectoryEndpoint = $loginEndpoint.TrimEnd('/') + "/"
- }
-
- $audiences = $authenticationData.audiences
- if($audiences.Count -gt 0)
- {
- $activeDirectoryServiceEndpointResourceId = $audiences[0]
- }
- }
-
- $graphEndpoint = $endpointData.graphEndpoint
- $graphAudience = $endpointData.graphEndpoint
- $galleryEndpoint = $endpointData.galleryEndpoint
- }
- }
- else
- {
- $aadAuthorityEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $graphEndpoint = $Endpoint.data.graphUrl
- $graphAudience = $Endpoint.data.graphUrl
- $activeDirectoryEndpoint = $Endpoint.data.ActiveDirectoryAuthority.Trim("/") + "/"
- $activeDirectoryServiceEndpointResourceId = $Endpoint.data.activeDirectoryServiceEndpointResourceId
- $galleryEndpoint = $Endpoint.data.galleryUrl
- }
-
- $azureEnvironmentParams = @{
- Name = $Name
- ActiveDirectoryEndpoint = $activeDirectoryEndpoint
- ActiveDirectoryServiceEndpointResourceId = $activeDirectoryServiceEndpointResourceId
- ResourceManagerEndpoint = $ResourceManagerEndpoint
- GalleryEndpoint = $galleryEndpoint
- GraphEndpoint = $graphEndpoint
- GraphAudience = $graphAudience
- StorageEndpointSuffix = $StorageEndpointSuffix
- AzureKeyVaultDnsSuffix = $AzureKeyVaultDnsSuffix
- AzureKeyVaultServiceEndpointResourceId = $AzureKeyVaultServiceEndpointResourceId
- EnableAdfsAuthentication = $aadAuthorityEndpoint.TrimEnd("/").EndsWith("/adfs", [System.StringComparison]::OrdinalIgnoreCase)
- }
-
- $armEnv = Get-AzureRmEnvironment -Name $name
- if($armEnv -ne $null) {
- Write-Verbose "Updating AzureRm environment $name" -Verbose
- Remove-AzureRmEnvironment -Name $name -Force | Out-Null
- }
- else {
- Write-Verbose "Adding AzureRm environment $name" -Verbose
- }
-
- return Add-AzureRmEnvironment @azureEnvironmentParams
-}
-
-function Get-ProxyUri
-{
- param([String] [Parameter(Mandatory=$true)] $serverUrl)
-
- $proxyUri = [System.Uri]($env:AGENT_PROXYURL)
- Write-Verbose -Verbose ("Reading proxy from the AGENT_PROXYURL environment variable. Proxy url specified={0}" -f $proxyUri.OriginalString)
-
- if($proxyUri -eq $null)
- {
- $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
- $proxyUri = $proxy.GetProxy("$serverUrl")
- Write-Verbose -Verbose ("Reading proxy from IE. Proxy url specified={0}" -f $proxyUri.OriginalString)
- }
-
- if($serverUrl -eq $null -or ([System.Uri]$serverUrl).Host -eq $proxyUri.Host)
- {
- return $null
- }
-
- return $proxyUri
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index c873f85..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Das Modul \"AzureRM.Profile\" wurde nicht gefunden. Das Modul \"AzureRM\" ist ggf. nicht vollständig installiert. Das Ausführen der folgenden PowerShell-Befehle aus einer Sitzung mit erhöhten Rechten behebt dieses Problem möglicherweise: \"Import-Module AzureRM\", \"Install-AzureRM\".",
- "loc.messages.AZ_CertificateAuthNotSupported": "Zertifikatbasierte Authentifizierung wird nicht unterstützt. Das Azure PowerShell-Modul wurde nicht gefunden.",
- "loc.messages.AZ_CredentialsError": "Fehler mit den für die Bereitstellung verwendeten Azure-Anmeldeinformationen.",
- "loc.messages.AZ_ModuleNotFound": "Das Azure-Modul und das AzureRM-Modul wurden nicht gefunden. Wenn das Modul vor Kurzem installiert wurde, versuchen Sie es nach dem Neustart des VSTS-Task-Agents erneut.",
- "loc.messages.AZ_RequiresMinVersion0": "Die erforderliche Mindestversion ({0}) des Azure PowerShell-Moduls ist nicht installiert.",
- "loc.messages.AZ_ServicePrincipalError": "Fehler im für die Bereitstellung verwendeten Dienstprinzipal.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Dienstprinzipalauthentifizierung wird in Version \"{0}\" des Azure-Moduls nicht unterstützt.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Nicht unterstütztes Authentifizierungsschema \"{0}\" für den Azure-Endpunkt."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index abbd1d8..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,12 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "loc.messages.AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "loc.messages.AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "loc.messages.AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "loc.messages.AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "loc.messages.AZ_AvailableModules": "The list of available {0} modules:",
- "loc.messages.AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index a8a03d3..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "No se encuentra el módulo 'AzureRM.Profile'. Puede que el módulo 'AzureRM' no esté instalado completamente. Puede resolver el problema ejecutando los siguientes comandos de PowerShell en una sesión con permisos elevados: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "No se admite la autenticación basada en certificados. No se encuentra el módulo Azure PowerShell.",
- "loc.messages.AZ_CredentialsError": "Hubo un error con las credenciales de Azure usadas para la implementación.",
- "loc.messages.AZ_ModuleNotFound": "No se encuentran ni el módulo Azure ni el módulo AzureRM. Si el módulo se instaló recientemente, vuelva a intentarlo después de reiniciar el agente de tareas de VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "No está instalada la versión mínima necesaria ({0}) del módulo Azure PowerShell.",
- "loc.messages.AZ_ServicePrincipalError": "Error con la entidad de servicio que se usó para la implementación.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "No se admite autenticación de entidad de servicio en la versión '{0}' del módulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Esquema de autenticación no admitido '{0}' para el punto de conexión de Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index c589189..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' introuvable. Le module 'AzureRM' n'est peut-être pas complètement installé. L'exécution des commandes PowerShell suivantes à partir d'une session avec élévation de privilèges peut éventuellement résoudre le problème : Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'authentification par certificat n'est pas prise en charge. Le module Azure PowerShell est introuvable.",
- "loc.messages.AZ_CredentialsError": "Une erreur s'est produite durant l'utilisation des informations d'identification Azure pour le déploiement.",
- "loc.messages.AZ_ModuleNotFound": "Les modules Azure et AzureRM sont introuvables. Si le module a été installé récemment, réessayez l'opération après avoir redémarré l'agent de tâche VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La version minimale nécessaire ({0}) pour le module Azure PowerShell n'est pas installée.",
- "loc.messages.AZ_ServicePrincipalError": "Erreur liée au principal du service utilisé pour le déploiement.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'authentification du principal du service n'est pas prise en charge dans la version '{0}' du module Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Modèle d'authentification '{0}' non pris en charge pour le point de terminaison Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index b91e443..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Il modulo 'AzureRM.Profile' non è stato trovato. È possibile che il modulo 'AzureRM' non sia completamente installato. Per risolvere il problema, provare a eseguire i comandi di PowerShell seguenti da una sessione con privilegi elevati: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "L'autenticazione basata su certificato non è supportata. Il modulo Azure PowerShell non è stato trovato.",
- "loc.messages.AZ_CredentialsError": "Si è verificato un errore con le credenziali di Azure usate per la distribuzione.",
- "loc.messages.AZ_ModuleNotFound": "Non è stato trovato né il modulo Azure né quello AzureRM. Se il modulo è stato installato di recente, riprovare dopo aver riavviato l'agente delle attività VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "La versione minima richiesta ({0}) del modulo Azure PowerShell non è installata.",
- "loc.messages.AZ_ServicePrincipalError": "Si è verificato un errore con l'entità servizio usata per la distribuzione.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "L'autenticazione basata su entità servizio non è supportata nella versione '{0}' del modulo Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Lo schema di autenticazione '{0}' non è supportato per l'endpoint di Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index 2e45631..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "モジュール 'AzureRM.Profile' が見つかりません。'AzureRM' モジュールが完全にインストールされていない可能性があります。管理者特権のセッションから次の PowerShell コマンドを実行すると、問題が解決する場合があります。Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "証明書に基づく認証はサポートされていません。Azure PowerShell モジュールが見つかりません。",
- "loc.messages.AZ_CredentialsError": "配置に使用した Azure 資格情報にエラーがありました。",
- "loc.messages.AZ_ModuleNotFound": "Azure モジュールも AzureRM モジュールも見つかりませんでした。モジュールが最近インストールされた場合、VSTS タスク エージェントの再始動後に再試行してください。",
- "loc.messages.AZ_RequiresMinVersion0": "必要な最小バージョン ({0}) の Azure PowerShell モジュールがインストールされていません。",
- "loc.messages.AZ_ServicePrincipalError": "配置に使用したサービス プリンシパルにエラーがありました。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "バージョン '{0}' の Azure モジュールでは、サービス プリンシパル認証はサポートされていません。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "'{0}' は Azure エンドポイントではサポートされていない認証スキームです。"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index ed3a33a..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "'AzureRM.Profile' 모듈을 찾을 수 없습니다. 'AzureRM' 모듈이 완전히 설치되지 않았을 수 있습니다. 관리자 권한 세션에서 다음 PowerShell 명령을 실행하면 이 문제가 해결될 수 있습니다. Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "인증서 기반 인증은 지원되지 않습니다. Azure PowerShell 모듈을 찾을 수 없습니다.",
- "loc.messages.AZ_CredentialsError": "배포에 사용되는 Azure 자격 증명에 오류가 발생했습니다.",
- "loc.messages.AZ_ModuleNotFound": "Azure 모듈과 AzureRM 모듈을 둘 다 찾을 수 없습니다. 모듈이 최근에 설치된 경우 VSTS 작업 에이전트를 다시 시작한 후 다시 시도하세요.",
- "loc.messages.AZ_RequiresMinVersion0": "필요한 Azure PowerShell 모듈의 최소 버전({0})이 설치되지 않았습니다.",
- "loc.messages.AZ_ServicePrincipalError": "배포에 사용되는 서비스 사용자에 오류가 발생했습니다.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "서비스 사용자 인증은 Azure 모듈의 '{0}' 버전에서 지원되지 않습니다.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 끝점에 대해 인증 체계 '{0}'은(는) 지원되지 않습니다."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index e8301e3..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "Модуль \"AzureRM.Profile\" не найден. Возможно, модуль \"AzureRM\" установлен не полностью. Выполнение следующих команд PowerShell из сеанса с повышенными правами может разрешить эту проблему: Import-Module AzureRM; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "Проверка подлинности на основе сертификатов не поддерживается. Модуль Azure PowerShell не найден.",
- "loc.messages.AZ_CredentialsError": "Произошла ошибка с учетными данными Azure, используемыми для развертывания.",
- "loc.messages.AZ_ModuleNotFound": "Не найдены модули Azure и AzureRM. Если модуль недавно установлен, повторите попытку после перезапуска агента задач VSTS.",
- "loc.messages.AZ_RequiresMinVersion0": "Минимальная требуемая версия ({0}) модуля Azure PowerShell не установлена.",
- "loc.messages.AZ_ServicePrincipalError": "Произошла ошибка с субъектом-службой, используемой для развертывания.",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Проверка подлинности на основе субъекта-службы не поддерживается в версии \"{0}\" модуля Azure.",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Схема аутентификации \"{0}\" не поддерживается для конечной точки Azure."
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 9741a56..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 \"AzureRM.Profile\" 模块。\"AzureRM\" 模块可能未完整安装。从提升的会话运行以下 PowerShell 命令可能解决该问题: Import-Module AzureRM;Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支持基于证书的身份验证。找不到 Azure PowerShell 模块。",
- "loc.messages.AZ_CredentialsError": "用于部署的 Azure 凭据有错。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模块和 AzureRM 模块。如果模块是最近安装的,请在重启 VSTS 任务代理后重试。",
- "loc.messages.AZ_RequiresMinVersion0": "未安装 Azure PowerShell 模块的最低必需版本({0})。",
- "loc.messages.AZ_ServicePrincipalError": "用于部署的服务主体有错。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Azure 模块的版本“{0}”不支持服务主体身份验证。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 终结点不支持授权方案“{0}”。"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index 4bc474f..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,10 +0,0 @@
-{
- "loc.messages.AZ_AzureRMProfileModuleNotFound": "找不到 'AzureRM.Profile' 模組。'AzureRM' 模組的安裝不完整。您可以從提升權限的工作階段執行下列 PowerShell 命令來解決此問題: Import-Module AzureRM ; Install-AzureRM",
- "loc.messages.AZ_CertificateAuthNotSupported": "不支援憑證型驗證。找不到 Azure PowerShell 模組。",
- "loc.messages.AZ_CredentialsError": "部署用的 Azure 認證有錯誤。",
- "loc.messages.AZ_ModuleNotFound": "找不到 Azure 模組,也找不到 AzureRM 模組。若最近才安裝該模組,請重新啟動 VSTS 工作代理程式,然後重試。",
- "loc.messages.AZ_RequiresMinVersion0": "未安裝所需最低版本 ({0}) 的 Azure PowerShell 模組。",
- "loc.messages.AZ_ServicePrincipalError": "部署用的服務主體有錯誤。",
- "loc.messages.AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "'{0}' 版的 Azure 模組不支援服務主體驗證。",
- "loc.messages.AZ_UnsupportedAuthScheme0": "Azure 端點不支援驗證配置 '{0}'。"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
deleted file mode 100644
index 50a94af..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzurePreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $null
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure' -azurePsVersion '4.1.0'
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
deleted file mode 100644
index 0e19719..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.AzureRMPreferredFallsBack.ps1
+++ /dev/null
@@ -1,63 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- RMModulePathResult = $true
- RMSdkPathResult = $null
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $true
- ClassicModulePathResult = $null
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- }
- @{
- RMModulePathResult = $false
- RMSdkPathResult = $false
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
deleted file mode 100644
index c64f79b..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.BothPreferredFallsBack.ps1
+++ /dev/null
@@ -1,89 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- # Combinations for only one preference matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $false
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $false
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- # Combinations for both preferences matched:
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $true
- ClassicSdkPathResult = $null
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $true
- RMSdkPathResult = $null
- }
- @{
- ClassicModulePathResult = $false
- ClassicSdkPathResult = $true
- RMModulePathResult = $false
- RMSdkPathResult = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
- if ($variableSet.RMModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.RMModulePathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.RMSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.RMSdkPathResult } -- -Classic: $false -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicModulePathResult -ne $null) {
- Register-Mock Import-FromModulePath { $variableSet.ClassicModulePathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- if ($variableSet.ClassicSdkPathResult -ne $null) {
- Register-Mock Import-FromSdkPath { $variableSet.ClassicSdkPathResult } -- -Classic: $true -azurePsVersion "4.1.0"
- }
-
- # Act.
- & $module Import-AzureModule -PreferredModule 'Azure', 'AzureRM' -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.RMModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.RMSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $false -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromModulePath -Times $(if ($variableSet.ClassicModulePathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
- Assert-WasCalled Import-FromSdkPath -Times $(if ($variableSet.ClassicSdkPathResult -eq $null) { 0 } else { 1 }) -- -Classic: $true -azurePsVersion "4.1.0"
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
deleted file mode 100644
index 2b31205..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ThrowsWhenNotFound.ps1
+++ /dev/null
@@ -1,21 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{ PreferredModule = 'Azure', 'AzureRM' }
- @{ PreferredModule = 'Azure' }
- @{ PreferredModule = 'AzureRM' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Import-FromModulePath
- Unregister-Mock Import-FromSdkPath
- Register-Mock Import-FromModulePath
- Register-Mock Import-FromSdkPath
-
- # Act/Assert.
- Assert-Throws { & $module Import-AzureModule -PreferredModule $variableSet.PreferredModule -azurePsVersion "4.1.0" } -MessagePattern "AZ_ModuleNotFound 4.1.0"
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
deleted file mode 100644
index f2af166..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-AzureModule.ValidatesClassicVersion.ps1
+++ /dev/null
@@ -1,11 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Import-FromModulePath { $true }
-& $module { $script:azureModule = @{ Version = [version]'0.8.10.0' } }
-
-# Act/Assert.
-Assert-Throws { & $module Import-AzureModule -PreferredModule 'Azure' } -MessagePattern AZ_RequiresMinVersion0*
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
deleted file mode 100644
index 82f7a0d..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ImportsModules.ps1
+++ /dev/null
@@ -1,66 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- Modules = @(
- @{
- Name = 'Azure'
- Path = 'Path to Azure'
- Version = [version]'4.1.0'
- }
- )
- }
- @{
- Classic = $false
- Modules = @(
- @{
- Name = 'AzureRM'
- Path = 'Path to AzureRM'
- Version = [version]'4.1.0'
- NestedModules = @(
- @{
- Name = 'AzureRM.Profile'
- Path = 'Path to AzureRM.profile'
- }
- )
- }
- @{
- Name = 'AzureRM.profile'
- Path = 'Path to AzureRM.profile'
- Version = [version]'4.1.0'
- }
- )
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-Module
- Unregister-Mock Import-Module
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name -ListAvailable
- Register-Mock Import-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Register-Mock Get-Module { $variableSet.Modules[0] } -- -Name $variableSet.Modules[0].Name
- Register-Mock Import-Module { $variableSet.Modules[1] } -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic) -azurePsVersion "4.1.0"
-
- # Assert.
- Assert-AreEqual $true $result
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[0].Path -Global -PassThru
- if ($variableSet.Modules.Length -eq 2) {
- Assert-WasCalled Import-Module -- -Name $variableSet.Modules[1].Path -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $variableSet.Modules[0] (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $variableSet.Modules[1] (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index 85f4e52..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,20 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-Register-Mock Get-Module
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
-
- # Act.
- $result = & $module Import-FromModulePath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $false $result
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
deleted file mode 100644
index 41674f1..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromModulePath.ValidatesRMProfileFound.ps1
+++ /dev/null
@@ -1,24 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$rmModule = @{ Name = 'AzureRM' ;
- Path = 'Path to AzureRM' ;
- Version = [version]'4.1.0' ;
- NestedModules = @(
- @{
- Name = "AzureRM.Websites"
- }
- @{
- Name = "AzureRM.Compute"
- }
- )
-}
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name -ListAvailable
-Register-Mock Get-Module { $rmModule } -- -Name $rmModule.Name
-Register-Mock Import-Module { $rmModule } -- -Name $rmModule.Path -RequiredVersion "4.1.0" -Global -PassThru
-
-# Act/Assert.
-Assert-Throws { & $module Import-FromModulePath -Classic:$false -azurePsVersion "4.1.0" } -MessagePattern AZ_AzureRMProfileModuleNotFound
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
deleted file mode 100644
index ded55eb..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ImportsModule.ps1
+++ /dev/null
@@ -1,111 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $true
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $false
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $false
- FoundInProgramFiles = $true
- }
- @{
- Classic = $false
- ProgramFilesX86Defined = $true
- FoundInProgramFilesX86 = $true
- FoundInProgramFiles = $true
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Test-Path
- Unregister-Mock Import-Module
-
- # Setup the expected partial path.
- if ($variableSet.Classic) {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Azure.psd1'
- } else {
- $partialPath = 'Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.Profile\AzureRM.Profile.psd1'
- }
-
- # Setup the Program Files environment variables.
- $env:ProgramFiles = 'program files'
- if ($variableSet.ProgramFilesX86Defined) {
- ${env:ProgramFiles(x86)} = 'wow program files' # Windows on Windows.
- } else {
- ${env:ProgramFiles(x86)} = ''
- }
-
- # Setup the PSD1 paths.
- $wowPsd1 = [System.IO.Path]::Combine(${env:ProgramFiles(x86)}, $partialPath)
- $psd1 = [System.IO.Path]::Combine($env:ProgramFiles, $partialPath)
-
- # Setup Test-Path.
- if ($variableSet.FoundInProgramFilesX86) {
- Register-Mock Test-Path { $true } -- -LiteralPath $wowPsd1 -PathType Leaf
- }
-
- if ($variableSet.FoundInProgramFiles) {
- Register-Mock Test-Path { $true } -- -LiteralPath $psd1 -PathType Leaf
- }
-
- # Setup Import-Module.
- if ($variableSet.FoundInProgramFilesX86) {
- $expectedModule = @{ Version = [version]'1.2.3.4' }
- Register-Mock Import-Module { $expectedModule } -Name $wowPsd1 -Global -PassThru
- }
-
- if ($variableSet.FoundInProgramFiles) {
- $expectedModule = @{ Version = [version]'2.3.4.5' }
- Register-Mock Import-Module { $expectedModule } -Name $psd1 -Global -PassThru
- }
-
- if($variableSet.Classic -eq $false) {
- Register-Mock Import-AzureRmSubmodulesFromSdkPath
- }
- # Clear the private module variables.
- & $module { $script:azureModule = $null ; $script:azureRMProfileModule = $null }
-
- # Act.
- $result = & $module Import-FromSdkPath -Classic:($variableSet.Classic)
-
- # Assert.
- Assert-AreEqual $true $result
- if ($variableSet.FoundInProgramFilesX86) {
- Assert-WasCalled Import-Module -- -Name $wowPsd1 -Global -PassThru
- } else {
- Assert-WasCalled Import-Module -- -Name $psd1 -Global -PassThru
- }
-
- if ($variableSet.Classic) {
- Assert-AreEqual $expectedModule (& $module { $script:azureModule })
- } else {
- Assert-AreEqual $expectedModule (& $module { $script:azureRMProfileModule })
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
deleted file mode 100644
index a84ae2b..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1
+++ /dev/null
@@ -1,22 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-# Setup the Program Files environment variables.
-$env:ProgramFiles = 'no such program files'
-${env:ProgramFiles(x86)} = 'no such program files x86'
-
-# Setup the mocks.
-Register-Mock Test-Path { $false }
-Unregister-Mock Import-Module
-Register-Mock Import-Module
-
-# Act.
-$result = & $module Import-FromSdkPath
-
-# Assert.
-Assert-AreEqual $false $result
-Assert-WasCalled Import-Module -Times 0
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
deleted file mode 100644
index a0bc268..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.PassesInputs.ps1
+++ /dev/null
@@ -1,98 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-$variableSets = @(
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'UserNamePassword' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = 'Azure', 'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceName'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceName'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = $null
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = 'ConnectedServiceNameARM'
- DeploymentEnvironmentName = $null
- Endpoint = @{ Auth = @{ Scheme = 'ServicePrincipal' } }
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'ConnectedServiceNameARM'
- ExpectedPreferredModule = ,'AzureRM'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = $null
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
- @{
- ConnectedServiceNameSelector = $null
- DeploymentEnvironmentName = 'Some deployment environment name'
- StorageAccount = 'Some storage account'
- ExpectedServiceNameInput = 'Some deployment environment name'
- ExpectedPreferredModule = ,'Azure'
- }
-)
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsInput
- Unregister-Mock Get-VstsEndpoint
- Register-Mock Get-VstsInput { $variableSet.ConnectedServiceNameSelector } -- -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- Register-Mock Get-VstsInput { $variableSet.DeploymentEnvironmentName } -- -Name DeploymentEnvironmentName
- Register-Mock Get-VstsInput { "LatestVersion" } -- -TargetAzurePs
- Register-Mock Get-VstsInput { 'Some service name' } -- -Name $variableSet.ExpectedServiceNameInput -Default $variableSet.DeploymentEnvironmentName
- Register-Mock Get-VstsEndpoint { $variableSet.Endpoint } -- -Name 'Some service name' -Require
- Register-Mock Get-VstsInput { $variableSet.StorageAccount } -- -Name StorageAccount
-
- # Act.
- Initialize-Azure
-
- # Assert.
- Assert-WasCalled Import-AzureModule -- -PreferredModule $variableSet.ExpectedPreferredModule -azurePsVersion ""
- Assert-WasCalled Initialize-AzureSubscription -- -Endpoint $variableSet.Endpoint -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
deleted file mode 100644
index a7afed1..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1
+++ /dev/null
@@ -1,13 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-Register-Mock Get-VstsInput { throw 'Some error message' } -- -Name $null -Require
-Register-Mock Get-VstsEndpoint
-Register-Mock Import-AzureModule
-Register-Mock Initialize-AzureSubscription
-
-# Act.
-Assert-Throws { Initialize-Azure } -MessagePattern 'Some error message'
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
deleted file mode 100644
index fb7ae08..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenAzureStackSPAuth.ps1
+++ /dev/null
@@ -1,83 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- Environment = 'AzureStack'
- }
-}
-$variableSets = @(
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- Register-Mock Add-AzureStackAzureRmEnvironment
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- $args[5] -eq '-Environment'
- $args[6] -eq 'AzureStack'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
deleted file mode 100644
index 1a0969e..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1
+++ /dev/null
@@ -1,46 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null }
- @{ StorageAccount = 'Some storage account' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment AzureCloud
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
deleted file mode 100644
index e1710f8..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1
+++ /dev/null
@@ -1,61 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureModule = @{ Version = [version]'1.0' } }
-$endpoint = @{
- Auth = @{
- Scheme = 'Certificate'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$certificate = 'Some certificate'
-$variableSets = @(
- @{ StorageAccount = $null ; EnvironmentName = $null}
- @{ StorageAccount = $null ; EnvironmentName = ""}
- @{ StorageAccount = $null ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = $null ; EnvironmentName = "AzureUSGovernment"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = $null}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = ""}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureCloud"}
- @{ StorageAccount = 'Some storage account' ; EnvironmentName = "AzureUSGovernment"}
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-Certificate
- Unregister-Mock Set-AzureSubscription
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-Certificate { $certificate }
- Register-Mock Set-AzureSubscription
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-UserAgent
-
- # Act.
- & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- if( $variableSet.Environment ){
- $environmentName = $variableSet.Environment
- }else{
- $environmentName = 'AzureCloud'
- }
-
- # setting environment to endpoint
- $endpoint.Data.Environment = $variableSet.Environment
-
- # Assert.
- Assert-WasCalled Add-Certificate -- -Endpoint $endpoint
- if ($variableSet.StorageAccount) {
- # The CurrentStorageAccountName parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName -CurrentStorageAccountName: $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionName $endpoint.Data.SubscriptionName -SubscriptionId $endpoint.Data.SubscriptionId -Certificate $certificate -Environment $environmentName
- }
-
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
deleted file mode 100644
index f0f93d5..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1
+++ /dev/null
@@ -1,81 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true ; StorageAccount = $null }
- @{ Classic = $true ; StorageAccount = 'Some storage account' }
- @{ Classic = $false ; StorageAccount = $null }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 5 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 7 -and
- $args[0] -eq '-ServicePrincipal' -and
- $args[1] -eq '-Tenant' -and
- $args[2] -eq 'Some tenant ID' -and
- $args[3] -eq '-Credential' -and
- $args[4] -is [pscredential] -and
- $args[4].UserName -eq 'Some service principal ID' -and
- $args[4].GetNetworkCredential().Password -eq 'Some service principal key'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -TenantId $endpoint.Auth.Parameters.TenantId
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
deleted file mode 100644
index 9d02f85..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1
+++ /dev/null
@@ -1,101 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- # Azure:
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $false
- StorageAccount = 'Some storage account'
- }
- # Azure and AzureRM:
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = $null
- }
- @{
- Azure = $true
- AzureRM = $true
- StorageAccount = 'Some storage account'
- }
- # AzureRM:
- @{
- Azure = $false
- AzureRM = $true
- StorageAccount = $null
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Set-CurrentAzureSubscription
- Unregister-Mock Set-CurrentAzureRMSubscription
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { 'some output' }
- Register-Mock Add-AzureRMAccount { 'some output' }
- Register-Mock Set-CurrentAzureSubscription
- Register-Mock Set-CurrentAzureRMSubscription
- Register-Mock Set-UserAgent
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = $null
- }
- if ($variableSet.Azure) {
- & $module { $script:azureModule = @{ Version = [version]'1.0' } }
- }
-
- if ($variableSet.AzureRM) {
- & $module { $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' } }
- }
-
- # Act.
- $result = & $module Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- Assert-AreEqual $null $result
- if ($variableSet.Azure) {
- Assert-WasCalled Add-AzureAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId -StorageAccount $variableSet.StorageAccount
- }
-
- if ($variableSet.AzureRM) {
- Assert-WasCalled Add-AzureRMAccount -ArgumentsEvaluator {
- $args.Length -eq 2 -and
- $args[0] -eq '-Credential' -and
- $args[1] -is [pscredential] -and
- $args[1].UserName -eq 'Some user name' -and
- $args[1].GetNetworkCredential().Password -eq 'Some password'
- }
- Assert-WasCalled Set-CurrentAzureRMSubscription -- -SubscriptionId $endpoint.Data.SubscriptionId
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
deleted file mode 100644
index 742dbcb..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,60 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'0.9.8' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_ServicePrincipalError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
deleted file mode 100644
index fa01e73..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1
+++ /dev/null
@@ -1,59 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- UserName = 'Some user name'
- Password = 'Some password'
- }
- Scheme = 'UserNamePassword'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Classic = $true }
- @{ Classic = $false }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Add-AzureAccount
- Unregister-Mock Add-AzureRMAccount
- Unregister-Mock Write-VstsTaskError
- Unregister-Mock Set-UserAgent
- Register-Mock Add-AzureAccount { throw 'Some add account error' }
- Register-Mock Add-AzureRMAccount { throw 'Some add account error' }
- Register-Mock Write-VstsTaskError
- Register-Mock Set-UserAgent
- if ($variableSet.Classic) {
- & $module {
- $script:azureModule = @{ Version = [version]'1.0' }
- $script:azureRMProfileModule = $null
- }
- } else {
- & $module {
- $script:azureModule = $null
- $script:azureRMProfileModule = @{ Version = [version]'1.2.3.4' }
- }
- }
-
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern AZ_CredentialsError
-
- # Assert.
- Assert-WasCalled Write-VstsTaskError -- -Message 'Some add account error'
- if ($variableSet.Classic) {
- Assert-WasCalled Add-AzureAccount
- } else {
- Assert-WasCalled Add-AzureRMAccount
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
deleted file mode 100644
index 76445a5..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-& $module { $script:azureRMProfileModule = @{ } }
-$endpoint = @{ Auth = @{ Scheme = 'Certificate' } }
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws { & $module Initialize-AzureSubscription -Endpoint $endpoint } -MessagePattern AZ_CertificateAuthNotSupported
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
deleted file mode 100644
index 984c7e9..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1
+++ /dev/null
@@ -1,36 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-Microsoft.PowerShell.Core\Import-Module Microsoft.PowerShell.Security
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'ServicePrincipal'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-$variableSets = @(
- @{ Version = [version]'0.9.9' }
- @{ Version = [version]'1.0' }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- Unregister-Mock Set-UserAgent
- Register-Mock Set-UserAgent
- # Act/Assert.
- Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
- } -MessagePattern "AZ_ServicePrincipalAuthNotSupportedAzureVersion0 $($variableSet.Version)"
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
deleted file mode 100644
index 6742061..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1
+++ /dev/null
@@ -1,26 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$endpoint = @{
- Auth = @{
- Parameters = @{
- ServicePrincipalId = 'Some service principal ID'
- ServicePrincipalKey = 'Some service principal key'
- TenantId = 'Some tenant ID'
- }
- Scheme = 'Some unknown scheme'
- }
- Data = @{
- SubscriptionId = 'Some subscription ID'
- SubscriptionName = 'Some subscription name'
- }
-}
-
-Register-Mock Set-UserAgent
-# Act/Assert.
-Assert-Throws {
- & $module Initialize-AzureSubscription -Endpoint $endpoint
-} -MessagePattern "AZ_UnsupportedAuthScheme0 Some unknown scheme"
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
deleted file mode 100644
index 9ccc5fb..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/L0.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-///
-///
-///
-
-import Q = require('q');
-import assert = require('assert');
-import path = require('path');
-var psm = require('../../../../Tests/lib/psRunner');
-var psr = null;
-
-describe('Common-VstsAzureHelpers_ Suite', function () {
- this.timeout(20000);
-
- before((done) => {
- if (psm.testSupported()) {
- psr = new psm.PSRunner();
- psr.start();
- }
-
- done();
- });
-
- after(function () {
- if (psr) {
- psr.kill();
- }
- });
-
- if (psm.testSupported()) {
- it('(Import-AzureModule) azure preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzurePreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) azure rm preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.AzureRMPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) both preferred falls back', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.BothPreferredFallsBack.ps1'), done);
- })
- it('(Import-AzureModule) throws when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ThrowsWhenNotFound.ps1'), done);
- })
- it('(Import-AzureModule) validates classic version', (done) => {
- psr.run(path.join(__dirname, 'Import-AzureModule.ValidatesClassicVersion.ps1'), done);
- })
- it('(Import-FromModulePath) imports modules', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ImportsModules.ps1'), done);
- })
- it('(Import-FromModulePath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Import-FromModulePath) validate RM profile found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromModulePath.ValidatesRMProfileFound.ps1'), done);
- })
- it('(Import-FromSdkPath) imports module', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ImportsModule.ps1'), done);
- })
- it('(Import-FromSdkPath) returns false when not found', (done) => {
- psr.run(path.join(__dirname, 'Import-FromSdkPath.ReturnsFalseWhenNotFound.ps1'), done);
- })
- it('(Initialize-Azure) passes inputs', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.PassesInputs.ps1'), done);
- })
- it('(Initialize-Azure) throws when service name is null', (done) => {
- psr.run(path.join(__dirname, 'Initialize-Azure.ThrowsWhenServiceNameIsNull.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when SP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenSPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when UP auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenUPAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when SP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenSPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws useful error when UP auth and add account fails', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsUsefulErrorWhenUPAuthAndAddAccountFails.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when RM and cert auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenRMAndCertAuth.ps1'), done);
- })
- it('(Initialize-AzureSubscription) passes values when cert auth and environment', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.PassesValuesWhenCertAuthAndEnvironment.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when SP auth and classic 0.9.9', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenSPAuthAndClassic099.ps1'), done);
- })
- it('(Initialize-AzureSubscription) throws when unsupported auth', (done) => {
- psr.run(path.join(__dirname, 'Initialize-AzureSubscription.ThrowsWhenUnsupportedAuth.ps1'), done);
- })
- it('(Set-CurrentAzureRMSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureRMSubscription.PassesValues.ps1'), done);
- })
- it('(Set-CurrentAzureSubscription) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-CurrentAzureSubscription.PassesValues.ps1'), done);
- })
- it('(Set-UserAgent) passes values', (done) => {
- psr.run(path.join(__dirname, 'Set-UserAgent.PassesValues.ps1'), done);
- })
- it('Overriddes global debug preference', (done) => {
- psr.run(path.join(__dirname, 'OverriddesGlobalDebugPreference.ps1'), done);
- })
- }
-});
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
deleted file mode 100644
index 9247699..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
+++ /dev/null
@@ -1,12 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$global:DebugPreference = 'Continue'
-
-# Act.
-Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\..
-
-# Assert.
-Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
deleted file mode 100644
index e3201bf..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureRMSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,32 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = $null
- }
- @{
- SubscriptionId = 'Some subscription ID'
- TenantId = 'Some tenant ID'
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureRMSubscription
- Register-Mock Select-AzureRMSubscription
-
- # Act.
- & $module Set-CurrentAzureRMSubscription -SubscriptionId $variableSet.SubscriptionId -TenantId $variableSet.TenantId
-
- # Assert.
- if ($variableSet.TenantId) {
- # The TenantId parameter ends in ":" for the assertion because it's splatted.
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId -TenantId: $variableSet.TenantId
- } else {
- Assert-WasCalled Select-AzureRMSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
deleted file mode 100644
index 6f4560f..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-CurrentAzureSubscription.PassesValues.ps1
+++ /dev/null
@@ -1,64 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-$variableSets = @(
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = $null
- ExpectDefaultSwitch = $false
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'0.8.14'
- StorageAccount = $null
- ExpectDefaultSwitch = $true
- }
- @{
- SubscriptionId = 'Some subscription ID'
- Version = [version]'1.0'
- StorageAccount = 'Some storage account'
- ExpectDefaultSwitch = $false
- }
-)
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Select-AzureSubscription
- Unregister-Mock Set-AzureSubscription
- Register-Mock Select-AzureSubscription
- Register-Mock Set-AzureSubscription
- & $module { $script:azureModule = @{ Version = $args[0] } } $variableSet.Version
-
- # Act.
- & $module Set-CurrentAzureSubscription -SubscriptionId $variableSet.SubscriptionId -StorageAccount $variableSet.StorageAccount
-
- # Assert.
- if ($variableSet.ExpectDefaultSwitch) {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -Default: $true
- } else {
- Assert-WasCalled Select-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId
- }
-
- if ($variableSet.StorageAccount) {
- Assert-WasCalled Set-AzureSubscription -- -SubscriptionId $variableSet.SubscriptionId -CurrentStorageAccountName $variableSet.StorageAccount
- } else {
- Assert-WasCalled Set-AzureSubscription -Times 0
- }
-}
-<#
-function Set-CurrentAzureRMSubscription {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$SubscriptionId,
- [string]$TenantId)
-
- $additional = @{ }
- if ($TenantId) { $additional['TenantId'] = $TenantId }
- Write-Host "##[command]Select-AzureRMSubscription -SubscriptionId $SubscriptionId $(Format-Splat $additional)"
- $null = Select-AzureRMSubscription -SubscriptionId $SubscriptionId @additional
-}
-#>
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
deleted file mode 100644
index 4459655..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/Tests/Set-UserAgent.PassesValues.ps1
+++ /dev/null
@@ -1,33 +0,0 @@
-[CmdletBinding()]
-param()
-
-# Arrange.
-. $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1
-$module = Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. -PassThru
-
-$variableSets = @(
- @{
- UserAgent = 'tfs_build'
- }
- @{
- UserAgent = ''
- }
-)
-
-foreach ($variableSet in $variableSets) {
- Write-Verbose ('-' * 80)
- Unregister-Mock Get-VstsTaskVariable
- Unregister-Mock Set-UserAgent_Core
- Register-Mock Get-VstsTaskVariable { $variableSet.UserAgent } -- -Name AZURE_HTTP_USER_AGENT
- Register-Mock Set-UserAgent_Core
-
- # Act.
- & $module Set-UserAgent
-
- # Assert.
- if ($variableSet.UserAgent) {
- Assert-WasCalled Set-UserAgent_Core -- -UserAgent 'tfs_build'
- } else {
- Assert-WasCalled Set-UserAgent_Core -Times 0
- }
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1 b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
deleted file mode 100644
index 398213f..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/VstsAzureHelpers_.psm1
+++ /dev/null
@@ -1,55 +0,0 @@
-# Private module-scope variables.
-$script:azureModule = $null
-$script:azureRMProfileModule = $null
-
-# Override the DebugPreference.
-if ($global:DebugPreference -eq 'Continue') {
- Write-Verbose '$OVERRIDING $global:DebugPreference from ''Continue'' to ''SilentlyContinue''.'
- $global:DebugPreference = 'SilentlyContinue'
-}
-
-# Import the loc strings.
-Import-VstsLocStrings -LiteralPath $PSScriptRoot/module.json
-
-# Dot source the private functions.
-. $PSScriptRoot/InitializeFunctions.ps1
-. $PSScriptRoot/ImportFunctions.ps1
-
-# This is the only public function.
-function Initialize-Azure {
- [CmdletBinding()]
- param( [string] $azurePsVersion )
- Trace-VstsEnteringInvocation $MyInvocation
- try {
- # Get the inputs.
- $serviceNameInput = Get-VstsInput -Name ConnectedServiceNameSelector -Default 'ConnectedServiceName'
- $serviceName = Get-VstsInput -Name $serviceNameInput -Default (Get-VstsInput -Name DeploymentEnvironmentName)
- if (!$serviceName) {
- # Let the task SDK throw an error message if the input isn't defined.
- Get-VstsInput -Name $serviceNameInput -Require
- }
-
- $endpoint = Get-VstsEndpoint -Name $serviceName -Require
- $storageAccount = Get-VstsInput -Name StorageAccount
-
- # Determine which modules are preferred.
- $preferredModules = @( )
- if ($endpoint.Auth.Scheme -eq 'ServicePrincipal') {
- $preferredModules += 'AzureRM'
- } elseif ($endpoint.Auth.Scheme -eq 'UserNamePassword') {
- $preferredModules += 'Azure'
- $preferredModules += 'AzureRM'
- } else {
- $preferredModules += 'Azure'
- }
-
- # Import/initialize the Azure module.
- Import-AzureModule -PreferredModule $preferredModules -azurePsVersion $azurePsVersion
- Initialize-AzureSubscription -Endpoint $endpoint -StorageAccount $storageAccount
- } finally {
- Trace-VstsLeavingInvocation $MyInvocation
- }
-}
-
-# Export only the public function.
-Export-ModuleMember -Function Initialize-Azure
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/module.json b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/module.json
deleted file mode 100644
index e770dec..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/module.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "messages": {
- "AZ_AzureRMProfileModuleNotFound": "Module 'AzureRM.Profile' not found. The 'AzureRM' module may not be fully installed. Running the following PowerShell commands from an elevated session may resolve the issue: Import-Module AzureRM ; Install-AzureRM",
- "AZ_CertificateAuthNotSupported": "Certificate based authentication is not supported. Azure PowerShell module is not found.",
- "AZ_CredentialsError": "There was an error with the Azure credentials used for the deployment.",
- "AZ_ModuleNotFound": "Neither the Azure module ('{0}') nor the AzureRM module ('{0}') was found. If the module was recently installed, retry after restarting the VSTS task agent.",
- "AZ_RequiresMinVersion0": "The required minimum version ({0}) of the Azure PowerShell module is not installed.",
- "AZ_ServicePrincipalError": "There was an error with the service principal used for the deployment.",
- "AZ_ServicePrincipalAuthNotSupportedAzureVersion0": "Service principal authentication is not supported in version '{0}' of the Azure module.",
- "AZ_UnsupportedAuthScheme0": "Unsupported authentication scheme '{0}' for Azure endpoint.",
- "AZ_AvailableModules": "The list of available {0} modules:",
- "AZ_InvalidARMEndpoint": "Specified AzureRM endpoint is invalid."
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/tsconfig.json b/apimwsdl/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
deleted file mode 100644
index 0438b79..0000000
--- a/apimwsdl/v2/ps_modules/VstsAzureHelpers_/tsconfig.json
+++ /dev/null
@@ -1,6 +0,0 @@
-{
- "compilerOptions": {
- "target": "ES6",
- "module": "commonjs"
- }
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
deleted file mode 100644
index 8687f1b..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/FindFunctions.ps1
+++ /dev/null
@@ -1,728 +0,0 @@
-<#
-.SYNOPSIS
-Finds files using match patterns.
-
-.DESCRIPTION
-Determines the find root from a list of patterns. Performs the find and then applies the glob patterns. Supports interleaved exclude patterns. Unrooted patterns are rooted using defaultRoot, unless matchOptions.matchBase is specified and the pattern is a basename only. For matchBase cases, the defaultRoot is used as the find root.
-
-.PARAMETER DefaultRoot
-Default path to root unrooted patterns. Falls back to System.DefaultWorkingDirectory or current location.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER FindOptions
-When the FindOptions parameter is not specified, defaults to (New-VstsFindOptions -FollowSymbolicLinksTrue). Following soft links is generally appropriate unless deleting files.
-
-.PARAMETER MatchOptions
-When the MatchOptions parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Find-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string]$DefaultRoot,
- [Parameter()]
- [string[]]$Pattern,
- $FindOptions,
- $MatchOptions)
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Apply defaults for parameters and trace.
- if (!$DefaultRoot) {
- $DefaultRoot = Get-TaskVariable -Name 'System.DefaultWorkingDirectory' -Default (Get-Location).Path
- }
-
- Write-Verbose "DefaultRoot: '$DefaultRoot'"
- if (!$FindOptions) {
- $FindOptions = New-FindOptions -FollowSpecifiedSymbolicLink -FollowSymbolicLinks
- }
-
- Trace-FindOptions -Options $FindOptions
- if (!$MatchOptions) {
- $MatchOptions = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $MatchOptions
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Normalize slashes for root dir.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- $results = @{ }
- $originalMatchOptions = $MatchOptions
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $MatchOptions = Copy-MatchOptions -Options $originalMatchOptions
-
- # Skip comments.
- if (!$MatchOptions.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $MatchOptions.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$MatchOptions.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$MatchOptions.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $MatchOptions.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $MatchOptions.NoNegate = $true
- $MatchOptions.FlipNegate = $false
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Expand braces - required to accurately interpret findPath.
- $expanded = $null
- $preExpanded = $pat
- if ($MatchOptions.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
- }
-
- # Set NoBrace.
- $MatchOptions.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- if ($isIncludePattern) {
- # Determine the findPath.
- $findInfo = Get-FindInfoFromPattern -DefaultRoot $DefaultRoot -Pattern $pat -MatchOptions $MatchOptions
- $findPath = $findInfo.FindPath
- Write-Verbose "FindPath: '$findPath'"
-
- if (!$findPath) {
- Write-Verbose "Skipping empty path."
- continue
- }
-
- # Perform the find.
- Write-Verbose "StatOnly: '$($findInfo.StatOnly)'"
- [string[]]$findResults = @( )
- if ($findInfo.StatOnly) {
- # Simply stat the path - all path segments were used to build the path.
- if ((Test-Path -LiteralPath $findPath)) {
- $findResults += $findPath
- }
- } else {
- $findResults = Get-FindResult -Path $findPath -Options $FindOptions
- }
-
- Write-Verbose "Found $($findResults.Count) paths."
-
- # Apply the pattern.
- Write-Verbose "Applying include pattern."
- if ($findInfo.AdjustedPattern -ne $pat) {
- Write-Verbose "AdjustedPattern: '$($findInfo.AdjustedPattern)'"
- $pat = $findInfo.AdjustedPattern
- }
-
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $findResults,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results[$matchResult.ToUpperInvariant()] = $matchResult
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Check if basename only and MatchBase=true.
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $pat) -and
- ($pat -replace '\\', '/').IndexOf('/') -lt 0) {
-
- # Do not root the pattern.
- Write-Verbose "MatchBase and basename only."
- } else {
- # Root the exclude pattern.
- $pat = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- [string[]]$results.Values,
- $pat,
- (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $results.Remove($matchResult.ToUpperInvariant())
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- $finalResult = @( $results.Values | Sort-Object )
- Write-Verbose "$($finalResult.Count) final results"
- return $finalResult
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Creates FindOptions for use with Find-VstsMatch.
-
-.DESCRIPTION
-Creates FindOptions for use with Find-VstsMatch. Contains switches to control whether to follow symlinks.
-
-.PARAMETER FollowSpecifiedSymbolicLink
-Indicates whether to traverse descendants if the specified path is a symbolic link directory. Does not cause nested symbolic link directories to be traversed.
-
-.PARAMETER FollowSymbolicLinks
-Indicates whether to traverse descendants of symbolic link directories.
-#>
-function New-FindOptions {
- [CmdletBinding()]
- param(
- [switch]$FollowSpecifiedSymbolicLink,
- [switch]$FollowSymbolicLinks)
-
- return New-Object psobject -Property @{
- FollowSpecifiedSymbolicLink = $FollowSpecifiedSymbolicLink.IsPresent
- FollowSymbolicLinks = $FollowSymbolicLinks.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch.
-
-.DESCRIPTION
-Creates MatchOptions for use with Find-VstsMatch and Select-VstsMatch. Contains switches to control which pattern matching options are applied.
-#>
-function New-MatchOptions {
- [CmdletBinding()]
- param(
- [switch]$Dot,
- [switch]$FlipNegate,
- [switch]$MatchBase,
- [switch]$NoBrace,
- [switch]$NoCase,
- [switch]$NoComment,
- [switch]$NoExt,
- [switch]$NoGlobStar,
- [switch]$NoNegate,
- [switch]$NoNull)
-
- return New-Object psobject -Property @{
- Dot = $Dot.IsPresent
- FlipNegate = $FlipNegate.IsPresent
- MatchBase = $MatchBase.IsPresent
- NoBrace = $NoBrace.IsPresent
- NoCase = $NoCase.IsPresent
- NoComment = $NoComment.IsPresent
- NoExt = $NoExt.IsPresent
- NoGlobStar = $NoGlobStar.IsPresent
- NoNegate = $NoNegate.IsPresent
- NoNull = $NoNull.IsPresent
- }
-}
-
-<#
-.SYNOPSIS
-Applies match patterns against a list of files.
-
-.DESCRIPTION
-Applies match patterns to a list of paths. Supports interleaved exclude patterns.
-
-.PARAMETER ItemPath
-Array of paths.
-
-.PARAMETER Pattern
-Patterns to apply. Supports interleaved exclude patterns.
-
-.PARAMETER PatternRoot
-Default root to apply to unrooted patterns. Not applied to basename-only patterns when Options.MatchBase is true.
-
-.PARAMETER Options
-When the Options parameter is not specified, defaults to (New-VstsMatchOptions -Dot -NoBrace -NoCase).
-#>
-function Select-Match {
- [CmdletBinding()]
- param(
- [Parameter()]
- [string[]]$ItemPath,
- [Parameter()]
- [string[]]$Pattern,
- [Parameter()]
- [string]$PatternRoot,
- $Options)
-
-
- Trace-EnteringInvocation $MyInvocation -Parameter None
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- if (!$Options) {
- $Options = New-MatchOptions -Dot -NoBrace -NoCase
- }
-
- Trace-MatchOptions -Options $Options
- Add-Type -LiteralPath $PSScriptRoot\Minimatch.dll
-
- # Hashtable to keep track of matches.
- $map = @{ }
-
- $originalOptions = $Options
- foreach ($pat in $Pattern) {
- Write-Verbose "Pattern: '$pat'"
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose 'Skipping empty pattern.'
- continue
- }
-
- # Clone match options.
- $Options = Copy-MatchOptions -Options $originalOptions
-
- # Skip comments.
- if (!$Options.NoComment -and $pat.StartsWith('#')) {
- Write-Verbose 'Skipping comment.'
- continue
- }
-
- # Set NoComment. Brace expansion could result in a leading '#'.
- $Options.NoComment = $true
-
- # Determine whether pattern is include or exclude.
- $negateCount = 0
- if (!$Options.NoNegate) {
- while ($negateCount -lt $pat.Length -and $pat[$negateCount] -eq '!') {
- $negateCount++
- }
-
- $pat = $pat.Substring($negateCount) # trim leading '!'
- if ($negateCount) {
- Write-Verbose "Trimmed leading '!'. Pattern: '$pat'"
- }
- }
-
- $isIncludePattern = $negateCount -eq 0 -or
- ($negateCount % 2 -eq 0 -and !$Options.FlipNegate) -or
- ($negateCount % 2 -eq 1 -and $Options.FlipNegate)
-
- # Set NoNegate. Brace expansion could result in a leading '!'.
- $Options.NoNegate = $true
- $Options.FlipNegate = $false
-
- # Expand braces - required to accurately root patterns.
- $expanded = $null
- $preExpanded = $pat
- if ($Options.NoBrace) {
- $expanded = @( $pat )
- } else {
- # Convert slashes on Windows before calling braceExpand(). Unfortunately this means braces cannot
- # be escaped on Windows, this limitation is consistent with current limitations of minimatch (3.0.3).
- Write-Verbose "Expanding braces."
- $convertedPattern = $pat -replace '\\', '/'
- $expanded = [Minimatch.Minimatcher]::BraceExpand(
- $convertedPattern,
- (ConvertTo-MinimatchOptions -Options $Options))
- }
-
- # Set NoBrace.
- $Options.NoBrace = $true
-
- foreach ($pat in $expanded) {
- if ($pat -ne $preExpanded) {
- Write-Verbose "Pattern: '$pat'"
- }
-
- # Trim and skip empty.
- $pat = "$pat".Trim()
- if (!$pat) {
- Write-Verbose "Skipping empty pattern."
- continue
- }
-
- # Root the pattern when all of the following conditions are true:
- if ($PatternRoot -and # PatternRoot is supplied
- !(Test-Rooted -Path $pat) -and # AND pattern is not rooted
- # # AND MatchBase=false or not basename only
- (!$Options.MatchBase -or ($pat -replace '\\', '/').IndexOf('/') -ge 0)) {
-
- # Root the include pattern.
- $pat = Get-RootedPattern -DefaultRoot $PatternRoot -Pattern $pat
- Write-Verbose "After Get-RootedPattern, pattern: '$pat'"
- }
-
- if ($isIncludePattern) {
- # Apply the pattern.
- Write-Verbose 'Applying include pattern against original list.'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Union the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map[$matchResult] = $true
- }
-
- Write-Verbose "$matchCount matches"
- } else {
- # Apply the pattern.
- Write-Verbose 'Applying exclude pattern against original list'
- $matchResults = [Minimatch.Minimatcher]::Filter(
- $ItemPath,
- $pat,
- (ConvertTo-MinimatchOptions -Options $Options))
-
- # Subtract the results.
- $matchCount = 0
- foreach ($matchResult in $matchResults) {
- $matchCount++
- $map.Remove($matchResult)
- }
-
- Write-Verbose "$matchCount matches"
- }
- }
- }
-
- # return a filtered version of the original list (preserves order and prevents duplication)
- $result = $ItemPath | Where-Object { $map[$_] }
- Write-Verbose "$($result.Count) final results"
- $result
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-################################################################################
-# Private functions.
-################################################################################
-
-function Copy-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- return New-Object psobject -Property @{
- Dot = $Options.Dot -eq $true
- FlipNegate = $Options.FlipNegate -eq $true
- MatchBase = $Options.MatchBase -eq $true
- NoBrace = $Options.NoBrace -eq $true
- NoCase = $Options.NoCase -eq $true
- NoComment = $Options.NoComment -eq $true
- NoExt = $Options.NoExt -eq $true
- NoGlobStar = $Options.NoGlobStar -eq $true
- NoNegate = $Options.NoNegate -eq $true
- NoNull = $Options.NoNull -eq $true
- }
-}
-
-function ConvertTo-MinimatchOptions {
- [CmdletBinding()]
- param($Options)
-
- $opt = New-Object Minimatch.Options
- $opt.AllowWindowsPaths = $true
- $opt.Dot = $Options.Dot -eq $true
- $opt.FlipNegate = $Options.FlipNegate -eq $true
- $opt.MatchBase = $Options.MatchBase -eq $true
- $opt.NoBrace = $Options.NoBrace -eq $true
- $opt.NoCase = $Options.NoCase -eq $true
- $opt.NoComment = $Options.NoComment -eq $true
- $opt.NoExt = $Options.NoExt -eq $true
- $opt.NoGlobStar = $Options.NoGlobStar -eq $true
- $opt.NoNegate = $Options.NoNegate -eq $true
- $opt.NoNull = $Options.NoNull -eq $true
- return $opt
-}
-
-function ConvertTo-NormalizedSeparators {
- [CmdletBinding()]
- param([string]$Path)
-
- # Convert slashes.
- $Path = "$Path".Replace('/', '\')
-
- # Remove redundant slashes.
- $isUnc = $Path -match '^\\\\+[^\\]'
- $Path = $Path -replace '\\\\+', '\'
- if ($isUnc) {
- $Path = '\' + $Path
- }
-
- return $Path
-}
-
-function Get-FindInfoFromPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern,
- [Parameter(Mandatory = $true)]
- $MatchOptions)
-
- if (!$MatchOptions.NoBrace) {
- throw "Get-FindInfoFromPattern expected MatchOptions.NoBrace to be true."
- }
-
- # For the sake of determining the find path, pretend NoCase=false.
- $MatchOptions = Copy-MatchOptions -Options $MatchOptions
- $MatchOptions.NoCase = $false
-
- # Check if basename only and MatchBase=true
- if ($MatchOptions.MatchBase -and
- !(Test-Rooted -Path $Pattern) -and
- ($Pattern -replace '\\', '/').IndexOf('/') -lt 0) {
-
- return New-Object psobject -Property @{
- AdjustedPattern = $Pattern
- FindPath = $DefaultRoot
- StatOnly = $false
- }
- }
-
- # The technique applied by this function is to use the information on the Minimatch object determine
- # the findPath. Minimatch breaks the pattern into path segments, and exposes information about which
- # segments are literal vs patterns.
- #
- # Note, the technique currently imposes a limitation for drive-relative paths with a glob in the
- # first segment, e.g. C:hello*/world. It's feasible to overcome this limitation, but is left unsolved
- # for now.
- $minimatchObj = New-Object Minimatch.Minimatcher($Pattern, (ConvertTo-MinimatchOptions -Options $MatchOptions))
-
- # The "set" field is a two-dimensional enumerable of parsed path segment info. The outer enumerable should only
- # contain one item, otherwise something went wrong. Brace expansion can result in multiple items in the outer
- # enumerable, but that should be turned off by the time this function is reached.
- #
- # Note, "set" is a private field in the .NET implementation but is documented as a feature in the nodejs
- # implementation. The .NET implementation is a port and is by a different author.
- $setFieldInfo = $minimatchObj.GetType().GetField('set', 'Instance,NonPublic')
- [object[]]$set = $setFieldInfo.GetValue($minimatchObj)
- if ($set.Count -ne 1) {
- throw "Get-FindInfoFromPattern expected Minimatch.Minimatcher(...).set.Count to be 1. Actual: '$($set.Count)'"
- }
-
- [string[]]$literalSegments = @( )
- [object[]]$parsedSegments = $set[0]
- foreach ($parsedSegment in $parsedSegments) {
- if ($parsedSegment.GetType().Name -eq 'LiteralItem') {
- # The item is a LiteralItem when the original input for the path segment does not contain any
- # unescaped glob characters.
- $literalSegments += $parsedSegment.Source;
- continue
- }
-
- break;
- }
-
- # Join the literal segments back together. Minimatch converts '\' to '/' on Windows, then squashes
- # consequetive slashes, and finally splits on slash. This means that UNC format is lost, but can
- # be detected from the original pattern.
- $joinedSegments = [string]::Join('/', $literalSegments)
- if ($joinedSegments -and ($Pattern -replace '\\', '/').StartsWith('//')) {
- $joinedSegments = '/' + $joinedSegments # restore UNC format
- }
-
- # Determine the find path.
- $findPath = ''
- if ((Test-Rooted -Path $Pattern)) { # The pattern is rooted.
- $findPath = $joinedSegments
- } elseif ($joinedSegments) { # The pattern is not rooted, and literal segements were found.
- $findPath = [System.IO.Path]::Combine($DefaultRoot, $joinedSegments)
- } else { # The pattern is not rooted, and no literal segements were found.
- $findPath = $DefaultRoot
- }
-
- # Clean up the path.
- if ($findPath) {
- $findPath = [System.IO.Path]::GetDirectoryName(([System.IO.Path]::Combine($findPath, '_'))) # Hack to remove unnecessary trailing slash.
- $findPath = ConvertTo-NormalizedSeparators -Path $findPath
- }
-
- return New-Object psobject -Property @{
- AdjustedPattern = Get-RootedPattern -DefaultRoot $DefaultRoot -Pattern $Pattern
- FindPath = $findPath
- StatOnly = $literalSegments.Count -eq $parsedSegments.Count
- }
-}
-
-function Get-FindResult {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- $Options)
-
- if (!(Test-Path -LiteralPath $Path)) {
- Write-Verbose 'Path not found.'
- return
- }
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
-
- # Push the first item.
- [System.Collections.Stack]$stack = New-Object System.Collections.Stack
- $stack.Push((Get-Item -LiteralPath $Path))
-
- $count = 0
- while ($stack.Count) {
- # Pop the next item and yield the result.
- $item = $stack.Pop()
- $count++
- $item.FullName
-
- # Traverse.
- if (($item.Attributes -band 0x00000010) -eq 0x00000010) { # Directory
- if (($item.Attributes -band 0x00000400) -ne 0x00000400 -or # ReparsePoint
- $Options.FollowSymbolicLinks -or
- ($count -eq 1 -and $Options.FollowSpecifiedSymbolicLink)) {
-
- $childItems = @( Get-DirectoryChildItem -Path $Item.FullName -Force )
- [System.Array]::Reverse($childItems)
- foreach ($childItem in $childItems) {
- $stack.Push($childItem)
- }
- }
- }
- }
-}
-
-function Get-RootedPattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$DefaultRoot,
- [Parameter(Mandatory = $true)]
- [string]$Pattern)
-
- if ((Test-Rooted -Path $Pattern)) {
- return $Pattern
- }
-
- # Normalize root.
- $DefaultRoot = ConvertTo-NormalizedSeparators -Path $DefaultRoot
-
- # Escape special glob characters.
- $DefaultRoot = $DefaultRoot -replace '(\[)(?=[^\/]+\])', '[[]' # Escape '[' when ']' follows within the path segment
- $DefaultRoot = $DefaultRoot.Replace('?', '[?]') # Escape '?'
- $DefaultRoot = $DefaultRoot.Replace('*', '[*]') # Escape '*'
- $DefaultRoot = $DefaultRoot -replace '\+\(', '[+](' # Escape '+('
- $DefaultRoot = $DefaultRoot -replace '@\(', '[@](' # Escape '@('
- $DefaultRoot = $DefaultRoot -replace '!\(', '[!](' # Escape '!('
-
- if ($DefaultRoot -like '[A-Z]:') { # e.g. C:
- return "$DefaultRoot$Pattern"
- }
-
- # Ensure root ends with a separator.
- if (!$DefaultRoot.EndsWith('\')) {
- $DefaultRoot = "$DefaultRoot\"
- }
-
- return "$DefaultRoot$Pattern"
-}
-
-function Test-Rooted {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- $Path = ConvertTo-NormalizedSeparators -Path $Path
- return $Path.StartsWith('\') -or # e.g. \ or \hello or \\hello
- $Path -like '[A-Z]:*' # e.g. C: or C:\hello
-}
-
-function Trace-MatchOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "MatchOptions.Dot: '$($Options.Dot)'"
- Write-Verbose "MatchOptions.FlipNegate: '$($Options.FlipNegate)'"
- Write-Verbose "MatchOptions.MatchBase: '$($Options.MatchBase)'"
- Write-Verbose "MatchOptions.NoBrace: '$($Options.NoBrace)'"
- Write-Verbose "MatchOptions.NoCase: '$($Options.NoCase)'"
- Write-Verbose "MatchOptions.NoComment: '$($Options.NoComment)'"
- Write-Verbose "MatchOptions.NoExt: '$($Options.NoExt)'"
- Write-Verbose "MatchOptions.NoGlobStar: '$($Options.NoGlobStar)'"
- Write-Verbose "MatchOptions.NoNegate: '$($Options.NoNegate)'"
- Write-Verbose "MatchOptions.NoNull: '$($Options.NoNull)'"
-}
-
-function Trace-FindOptions {
- [CmdletBinding()]
- param($Options)
-
- Write-Verbose "FindOptions.FollowSpecifiedSymbolicLink: '$($FindOptions.FollowSpecifiedSymbolicLink)'"
- Write-Verbose "FindOptions.FollowSymbolicLinks: '$($FindOptions.FollowSymbolicLinks)'"
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
deleted file mode 100644
index 21c4ade..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/InputFunctions.ps1
+++ /dev/null
@@ -1,425 +0,0 @@
-# Hash table of known variable info. The formatted env var name is the lookup key.
-#
-# The purpose of this hash table is to keep track of known variables. The hash table
-# needs to be maintained for multiple reasons:
-# 1) to distinguish between env vars and job vars
-# 2) to distinguish between secret vars and public
-# 3) to know the real variable name and not just the formatted env var name.
-$script:knownVariables = @{ }
-$script:vault = @{ }
-
-<#
-.SYNOPSIS
-Gets an endpoint.
-
-.DESCRIPTION
-Gets an endpoint object for the specified endpoint name. The endpoint is returned as an object with three properties: Auth, Data, and Url.
-
-The Data property requires a 1.97 agent or higher.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-Endpoint {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [switch]$Require)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the URL.
- $description = Get-LocString -Key PSLIB_EndpointUrl0 -ArgumentList $Name
- $key = "ENDPOINT_URL_$Name"
- $url = Get-VaultValue -Description $description -Key $key -Require:$Require
-
- # Get the auth object.
- $description = Get-LocString -Key PSLIB_EndpointAuth0 -ArgumentList $Name
- $key = "ENDPOINT_AUTH_$Name"
- if ($auth = (Get-VaultValue -Description $description -Key $key -Require:$Require)) {
- $auth = ConvertFrom-Json -InputObject $auth
- }
-
- # Get the data.
- $description = "'$Name' service endpoint data"
- $key = "ENDPOINT_DATA_$Name"
- if ($data = (Get-VaultValue -Description $description -Key $key)) {
- $data = ConvertFrom-Json -InputObject $data
- }
-
- # Return the endpoint.
- if ($url -or $auth -or $data) {
- New-Object -TypeName psobject -Property @{
- Url = $url
- Auth = $auth
- Data = $data
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets an input.
-
-.DESCRIPTION
-Gets the value for the specified input name.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-Input {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Get the input from the vault. Splat the bound parameters hashtable. Splatting is required
- # in order to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $description = Get-LocString -Key PSLIB_Input0 -ArgumentList $Name
- $key = "INPUT_$($Name.Replace(' ', '_').ToUpperInvariant())"
- Get-VaultValue @PSBoundParameters -Description $description -Key $key
-}
-
-<#
-.SYNOPSIS
-Gets a task variable.
-
-.DESCRIPTION
-Gets the value for the specified task variable.
-
-.PARAMETER AsBool
-Returns the value as a bool. Returns true if the value converted to a string is "1" or "true" (case insensitive); otherwise false.
-
-.PARAMETER AsInt
-Returns the value as an int. Returns the value converted to an int. Returns 0 if the conversion fails.
-
-.PARAMETER Default
-Default value to use if the input is null or empty.
-
-.PARAMETER Require
-Writes an error to the error pipeline if the input is null or empty.
-#>
-function Get-TaskVariable {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(ParameterSetName = 'Default')]
- $Default,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
- $description = Get-LocString -Key PSLIB_TaskVariable0 -ArgumentList $Name
- $variableKey = Get-VariableKey -Name $Name
- if ($script:knownVariables.$variableKey.Secret) {
- # Get secret variable. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- $vaultKey = "SECRET_$variableKey"
- Get-VaultValue @PSBoundParameters -Description $description -Key $vaultKey
- } else {
- # Get public variable.
- $item = $null
- $path = "Env:$variableKey"
- if ((Test-Path -LiteralPath $path) -and ($item = Get-Item -LiteralPath $path).Value) {
- # Intentionally empty. Value was successfully retrieved.
- } elseif (!$script:nonInteractive) {
- # The value wasn't found and the module is running in interactive dev mode.
- # Prompt for the value.
- Set-Item -LiteralPath $path -Value (Read-Host -Prompt $description)
- if (Test-Path -LiteralPath $path) {
- $item = Get-Item -LiteralPath $path
- }
- }
-
- # Get the converted value. Splatting is required to concisely invoke the correct parameter set.
- $null = $PSBoundParameters.Remove('Name')
- Get-Value @PSBoundParameters -Description $description -Key $variableKey -Value $item.Value
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- }
-}
-
-<#
-.SYNOPSIS
-Gets all job variables available to the task. Requires 2.104.1 agent or higher.
-
-.DESCRIPTION
-Gets a snapshot of the current state of all job variables available to the task.
-Requires a 2.104.1 agent or higher for full functionality.
-
-Returns an array of objects with the following properties:
- [string]Name
- [string]Value
- [bool]Secret
-
-Limitations on an agent prior to 2.104.1:
- 1) The return value does not include all public variables. Only public variables
- that have been added using setVariable are returned.
- 2) The name returned for each secret variable is the formatted environment variable
- name, not the actual variable name (unless it was set explicitly at runtime using
- setVariable).
-#>
-function Get-TaskVariableInfo {
- [CmdletBinding()]
- param()
-
- foreach ($info in $script:knownVariables.Values) {
- New-Object -TypeName psobject -Property @{
- Name = $info.Name
- Value = Get-TaskVariable -Name $info.Name
- Secret = $info.Secret
- }
- }
-}
-
-<#
-.SYNOPSIS
-Sets a task variable.
-
-.DESCRIPTION
-Sets a task variable in the current task context as well as in the current job context. This allows the task variable to retrieved by subsequent tasks within the same job.
-#>
-function Set-TaskVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret)
-
- # Once a secret always a secret.
- $variableKey = Get-VariableKey -Name $Name
- [bool]$Secret = $Secret -or $script:knownVariables.$variableKey.Secret
- if ($Secret) {
- $vaultKey = "SECRET_$variableKey"
- if (!$Value) {
- # Clear the secret.
- Write-Verbose "Set $Name = ''"
- $script:vault.Remove($vaultKey)
- } else {
- # Store the secret in the vault.
- Write-Verbose "Set $Name = '********'"
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Set-Item -LiteralPath "Env:$variableKey" -Value ''
- } else {
- # Set the environment variable.
- Write-Verbose "Set $Name = '$Value'"
- Set-Item -LiteralPath "Env:$variableKey" -Value $Value
- }
-
- # Store the metadata.
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $Secret
- }
-
- # Persist the variable in the task context.
- Write-SetVariable -Name $Name -Value $Value -Secret:$Secret
-}
-
-########################################
-# Private functions.
-########################################
-function Get-VaultValue {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- # Attempt to get the vault value.
- $value = $null
- if ($psCredential = $script:vault[$Key]) {
- $value = $psCredential.GetNetworkCredential().Password
- } elseif (!$script:nonInteractive) {
- # The value wasn't found. Prompt for the value if running in interactive dev mode.
- $value = Read-Host -Prompt $Description
- if ($value) {
- $script:vault[$Key] = New-Object System.Management.Automation.PSCredential(
- $Key,
- (ConvertTo-SecureString -String $value -AsPlainText -Force))
- }
- }
-
- Get-Value -Value $value @PSBoundParameters
-}
-
-function Get-Value {
- [CmdletBinding(DefaultParameterSetName = 'Require')]
- param(
- [string]$Value,
- [Parameter(Mandatory = $true)]
- [string]$Description,
- [Parameter(Mandatory = $true)]
- [string]$Key,
- [Parameter(ParameterSetName = 'Require')]
- [switch]$Require,
- [Parameter(ParameterSetName = 'Default')]
- [object]$Default,
- [switch]$AsBool,
- [switch]$AsInt)
-
- $result = $Value
- if ($result) {
- if ($Key -like 'ENDPOINT_AUTH_*') {
- Write-Verbose "$($Key): '********'"
- } else {
- Write-Verbose "$($Key): '$result'"
- }
- } else {
- Write-Verbose "$Key (empty)"
-
- # Write error if required.
- if ($Require) {
- Write-Error "$(Get-LocString -Key PSLIB_Required0 $Description)"
- return
- }
-
- # Fallback to the default if provided.
- if ($PSCmdlet.ParameterSetName -eq 'Default') {
- $result = $Default
- $OFS = ' '
- Write-Verbose " Defaulted to: '$result'"
- } else {
- $result = ''
- }
- }
-
- # Convert to bool if specified.
- if ($AsBool) {
- if ($result -isnot [bool]) {
- $result = "$result" -in '1', 'true'
- Write-Verbose " Converted to bool: $result"
- }
-
- return $result
- }
-
- # Convert to int if specified.
- if ($AsInt) {
- if ($result -isnot [int]) {
- try {
- $result = [int]"$result"
- } catch {
- $result = 0
- }
-
- Write-Verbose " Converted to int: $result"
- }
-
- return $result
- }
-
- return $result
-}
-
-function Initialize-Inputs {
- # Store endpoints, inputs, and secret variables in the vault.
- foreach ($variable in (Get-ChildItem -Path Env:ENDPOINT_?*, Env:INPUT_?*, Env:SECRET_?*, Env:SECUREFILE_?*)) {
- # Record the secret variable metadata. This is required by Get-TaskVariable to
- # retrieve the value. In a 2.104.1 agent or higher, this metadata will be overwritten
- # when $env:VSTS_SECRET_VARIABLES is processed.
- if ($variable.Name -like 'SECRET_?*') {
- $variableKey = $variable.Name.Substring('SECRET_'.Length)
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- # This is technically not the variable name (has underscores instead of dots),
- # but it's good enough to make Get-TaskVariable work in a pre-2.104.1 agent
- # where $env:VSTS_SECRET_VARIABLES is not defined.
- Name = $variableKey
- Secret = $true
- }
- }
-
- # Store the value in the vault.
- $vaultKey = $variable.Name
- if ($variable.Value) {
- $script:vault[$vaultKey] = New-Object System.Management.Automation.PSCredential(
- $vaultKey,
- (ConvertTo-SecureString -String $variable.Value -AsPlainText -Force))
- }
-
- # Clear the environment variable.
- Remove-Item -LiteralPath "Env:$($variable.Name)"
- }
-
- # Record the public variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_PUBLIC_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_PUBLIC_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $false
- }
- }
-
- $env:VSTS_PUBLIC_VARIABLES = ''
- }
-
- # Record the secret variable names. Env var added in 2.104.1 agent.
- if ($env:VSTS_SECRET_VARIABLES) {
- foreach ($name in (ConvertFrom-Json -InputObject $env:VSTS_SECRET_VARIABLES)) {
- $variableKey = Get-VariableKey -Name $name
- $script:knownVariables[$variableKey] = New-Object -TypeName psobject -Property @{
- Name = $name
- Secret = $true
- }
- }
-
- $env:VSTS_SECRET_VARIABLES = ''
- }
-}
-
-function Get-VariableKey {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name)
-
- if ($Name -ne 'agent.jobstatus') {
- $Name = $Name.Replace('.', '_')
- }
-
- $Name.ToUpperInvariant()
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
deleted file mode 100644
index f6aaa5a..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/LegacyFindFunctions.ps1
+++ /dev/null
@@ -1,320 +0,0 @@
-<#
-.SYNOPSIS
-Finds files or directories.
-
-.DESCRIPTION
-Finds files or directories using advanced pattern matching.
-
-.PARAMETER LiteralDirectory
-Directory to search.
-
-.PARAMETER LegacyPattern
-Proprietary pattern format. The LiteralDirectory parameter is used to root any unrooted patterns.
-
-Separate multiple patterns using ";". Escape actual ";" in the path by using ";;".
-"?" indicates a wildcard that represents any single character within a path segment.
-"*" indicates a wildcard that represents zero or more characters within a path segment.
-"**" as the entire path segment indicates a recursive search.
-"**" within a path segment indicates a recursive intersegment wildcard.
-"+:" (can be omitted) indicates an include pattern.
-"-:" indicates an exclude pattern.
-
-The result is from the command is a union of all the matches from the include patterns, minus the matches from the exclude patterns.
-
-.PARAMETER IncludeFiles
-Indicates whether to include files in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER IncludeDirectories
-Indicates whether to include directories in the results.
-
-If neither IncludeFiles or IncludeDirectories is set, then IncludeFiles is assumed.
-
-.PARAMETER Force
-Indicates whether to include hidden items.
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is?Match.txt"
-
-Given:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-C:\Directory\IsNotMatch.txt
-
-Returns:
-C:\Directory\Is1Match.txt
-C:\Directory\Is2Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Is*Match.txt"
-
-Given:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-C:\Directory\NonMatch.txt
-
-Returns:
-C:\Directory\IsOneMatch.txt
-C:\Directory\IsTwoMatch.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**\Match.txt"
-
-Given:
-C:\Directory\Match.txt
-C:\Directory\NotAMatch.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-Returns:
-C:\Directory\Match.txt
-C:\Directory\SubDir\Match.txt
-C:\Directory\SubDir\SubSubDir\Match.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\**"
-
-Given:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-Returns:
-C:\Directory\One.txt
-C:\Directory\SubDir\Two.txt
-C:\Directory\SubDir\SubSubDir\Three.txt
-
-.EXAMPLE
-Find-VstsFiles -LegacyPattern "C:\Directory\Sub**Match.txt"
-
-Given:
-C:\Directory\IsNotAMatch.txt
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\IsNot.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsNot.txt
-
-Returns:
-C:\Directory\SubDir\IsAMatch.txt
-C:\Directory\SubDir\SubSubDir\IsAMatch.txt
-#>
-function Find-Files {
- [CmdletBinding()]
- param(
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$LiteralDirectory,
- [Parameter(Mandatory = $true)]
- [string]$LegacyPattern,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- # Note, due to subtle implementation details of Get-PathPrefix/Get-PathIterator,
- # this function does not appear to be able to search the root of a drive and other
- # cases where Path.GetDirectoryName() returns empty. More details in Get-PathPrefix.
-
- Trace-EnteringInvocation $MyInvocation
- if (!$IncludeFiles -and !$IncludeDirectories) {
- $IncludeFiles = $true
- }
-
- $includePatterns = New-Object System.Collections.Generic.List[string]
- $excludePatterns = New-Object System.Collections.Generic.List[System.Text.RegularExpressions.Regex]
- $LegacyPattern = $LegacyPattern.Replace(';;', "`0")
- foreach ($pattern in $LegacyPattern.Split(';', [System.StringSplitOptions]::RemoveEmptyEntries)) {
- $pattern = $pattern.Replace("`0", ';')
- $isIncludePattern = Test-IsIncludePattern -Pattern ([ref]$pattern)
- if ($LiteralDirectory -and !([System.IO.Path]::IsPathRooted($pattern))) {
- # Use the root directory provided to make the pattern a rooted path.
- $pattern = [System.IO.Path]::Combine($LiteralDirectory, $pattern)
- }
-
- # Validate pattern does not end with a \.
- if ($pattern[$pattern.Length - 1] -eq [System.IO.Path]::DirectorySeparatorChar) {
- throw (Get-LocString -Key PSLIB_InvalidPattern0 -ArgumentList $pattern)
- }
-
- if ($isIncludePattern) {
- $includePatterns.Add($pattern)
- } else {
- $excludePatterns.Add((Convert-PatternToRegex -Pattern $pattern))
- }
- }
-
- $count = 0
- foreach ($path in (Get-MatchingItems -IncludePatterns $includePatterns -ExcludePatterns $excludePatterns -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force)) {
- $count++
- $path
- }
-
- Write-Verbose "Total found: $count"
- Trace-LeavingInvocation $MyInvocation
-}
-
-########################################
-# Private functions.
-########################################
-function Convert-PatternToRegex {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $Pattern = [regex]::Escape($Pattern.Replace('\', '/')). # Normalize separators and regex escape.
- Replace('/\*\*/', '((/.+/)|(/))'). # Replace directory globstar.
- Replace('\*\*', '.*'). # Replace remaining globstars with a wildcard that can span directory separators.
- Replace('\*', '[^/]*'). # Replace asterisks with a wildcard that cannot span directory separators.
- # bug: should be '[^/]' instead of '.'
- Replace('\?', '.') # Replace single character wildcards.
- New-Object regex -ArgumentList "^$Pattern`$", ([System.Text.RegularExpressions.RegexOptions]::IgnoreCase)
-}
-
-function Get-FileNameFilter {
- [CmdletBinding()]
- param([string]$Pattern)
-
- $index = $Pattern.LastIndexOf('\')
- if ($index -eq -1 -or # Pattern does not contain a backslash.
- !($Pattern = $Pattern.Substring($index + 1)) -or # Pattern ends in a backslash.
- $Pattern.Contains('**')) # Last segment contains an inter-segment wildcard.
- {
- return '*'
- }
-
- # bug? is this supposed to do substring?
- return $Pattern
-}
-
-function Get-MatchingItems {
- [CmdletBinding()]
- param(
- [System.Collections.Generic.List[string]]$IncludePatterns,
- [System.Collections.Generic.List[regex]]$ExcludePatterns,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- Trace-EnteringInvocation $MyInvocation
- $allFiles = New-Object System.Collections.Generic.HashSet[string]
- foreach ($pattern in $IncludePatterns) {
- $pathPrefix = Get-PathPrefix -Pattern $pattern
- $fileNameFilter = Get-FileNameFilter -Pattern $pattern
- $patternRegex = Convert-PatternToRegex -Pattern $pattern
- # Iterate over the directories and files under the pathPrefix.
- Get-PathIterator -Path $pathPrefix -Filter $fileNameFilter -IncludeFiles:$IncludeFiles -IncludeDirectories:$IncludeDirectories -Force:$Force |
- ForEach-Object {
- # Normalize separators.
- $normalizedPath = $_.Replace('\', '/')
- # **/times/** will not match C:/fun/times because there isn't a trailing slash.
- # So try both if including directories.
- $alternatePath = "$normalizedPath/" # potential bug: it looks like this will result in a false
- # positive if the item is a regular file and not a directory
-
- $isMatch = $false
- if ($patternRegex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $patternRegex.IsMatch($alternatePath))) {
- $isMatch = $true
-
- # Test whether the path should be excluded.
- foreach ($regex in $ExcludePatterns) {
- if ($regex.IsMatch($normalizedPath) -or ($IncludeDirectories -and $regex.IsMatch($alternatePath))) {
- $isMatch = $false
- break
- }
- }
- }
-
- if ($isMatch) {
- $null = $allFiles.Add($_)
- }
- }
- }
-
- Trace-Path -Path $allFiles -PassThru
- Trace-LeavingInvocation $MyInvocation
-}
-
-function Get-PathIterator {
- [CmdletBinding()]
- param(
- [string]$Path,
- [string]$Filter,
- [switch]$IncludeFiles,
- [switch]$IncludeDirectories,
- [switch]$Force)
-
- if (!$Path) {
- return
- }
-
- # bug: this returns the dir without verifying whether exists
- if ($IncludeDirectories) {
- $Path
- }
-
- Get-DirectoryChildItem -Path $Path -Filter $Filter -Force:$Force -Recurse |
- ForEach-Object {
- if ($_.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- if ($IncludeDirectories) {
- $_.FullName
- }
- } elseif ($IncludeFiles) {
- $_.FullName
- }
- }
-}
-
-function Get-PathPrefix {
- [CmdletBinding()]
- param([string]$Pattern)
-
- # Note, unable to search root directories is a limitation due to subtleties of this function
- # and downstream code in Get-PathIterator that short-circuits when the path prefix is empty.
- # This function uses Path.GetDirectoryName() to determine the path prefix, which will yield
- # empty in some cases. See the following examples of Path.GetDirectoryName() input => output:
- # C:/ =>
- # C:/hello => C:\
- # C:/hello/ => C:\hello
- # C:/hello/world => C:\hello
- # C:/hello/world/ => C:\hello\world
- # C: =>
- # C:hello => C:
- # C:hello/ => C:hello
- # / =>
- # /hello => \
- # /hello/ => \hello
- # //hello =>
- # //hello/ =>
- # //hello/world =>
- # //hello/world/ => \\hello\world
-
- $index = $Pattern.IndexOfAny([char[]]@('*'[0], '?'[0]))
- if ($index -eq -1) {
- # If no wildcards are found, return the directory name portion of the path.
- # If there is no directory name (file name only in pattern), this will return empty string.
- return [System.IO.Path]::GetDirectoryName($Pattern)
- }
-
- [System.IO.Path]::GetDirectoryName($Pattern.Substring(0, $index))
-}
-
-function Test-IsIncludePattern {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [ref]$Pattern)
-
- # Include patterns start with +: or anything except -:
- # Exclude patterns start with -:
- if ($Pattern.value.StartsWith("+:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $true
- } elseif ($Pattern.value.StartsWith("-:")) {
- # Remove the prefix.
- $Pattern.value = $Pattern.value.Substring(2)
- $false
- } else {
- # No prefix, so leave the string alone.
- $true;
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
deleted file mode 100644
index 6f3b6bb..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/LocalizationFunctions.ps1
+++ /dev/null
@@ -1,150 +0,0 @@
-$script:resourceStrings = @{ }
-
-<#
-.SYNOPSIS
-Gets a localized resource string.
-
-.DESCRIPTION
-Gets a localized resource string and optionally formats the string with arguments.
-
-If the format fails (due to a bad format string or incorrect expected arguments in the format string), then the format string is returned followed by each of the arguments (delimited by a space).
-
-If the lookup key is not found, then the lookup key is returned followed by each of the arguments (delimited by a space).
-
-.PARAMETER Require
-Writes an error to the error pipeline if the endpoint is not found.
-#>
-function Get-LocString {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true, Position = 1)]
- [string]$Key,
- [Parameter(Position = 2)]
- [object[]]$ArgumentList = @( ))
-
- # Due to the dynamically typed nature of PowerShell, a single null argument passed
- # to an array parameter is interpreted as a null array.
- if ([object]::ReferenceEquals($null, $ArgumentList)) {
- $ArgumentList = @( $null )
- }
-
- # Lookup the format string.
- $format = ''
- if (!($format = $script:resourceStrings[$Key])) {
- # Warn the key was not found. Prevent recursion if the lookup key is the
- # "string resource key not found" lookup key.
- $resourceNotFoundKey = 'PSLIB_StringResourceKeyNotFound0'
- if ($key -ne $resourceNotFoundKey) {
- Write-Warning (Get-LocString -Key $resourceNotFoundKey -ArgumentList $Key)
- }
-
- # Fallback to just the key itself if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $key }
-
- # Otherwise fallback to the key followed by the arguments.
- $OFS = " "
- return "$key $ArgumentList"
- }
-
- # Return the string if there aren't any arguments to format.
- if (!$ArgumentList.Count) { return $format }
-
- try {
- [string]::Format($format, $ArgumentList)
- } catch {
- Write-Warning (Get-LocString -Key 'PSLIB_StringFormatFailed')
- $OFS = " "
- "$format $ArgumentList"
- }
-}
-
-<#
-.SYNOPSIS
-Imports resource strings for use with Get-VstsLocString.
-
-.DESCRIPTION
-Imports resource strings for use with Get-VstsLocString. The imported strings are stored in an internal resource string dictionary. Optionally, if a separate resource file for the current culture exists, then the localized strings from that file then imported (overlaid) into the same internal resource string dictionary.
-
-Resource strings from the SDK are prefixed with "PSLIB_". This prefix should be avoided for custom resource strings.
-
-.Parameter LiteralPath
-JSON file containing resource strings.
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Imports strings from messages section in the JSON file. If a messages section is not defined, then no strings are imported. Example messages section:
-{
- "messages": {
- "Hello": "Hello you!",
- "Hello0": "Hello {0}!"
- }
-}
-
-.EXAMPLE
-Import-VstsLocStrings -LiteralPath $PSScriptRoot\Task.json
-
-Overlays strings from an optional separate resource file for the current culture.
-
-Given the task variable System.Culture is set to 'de-DE'. This variable is set by the agent based on the current culture for the job.
-Given the file Task.json contains:
-{
- "messages": {
- "GoodDay": "Good day!",
- }
-}
-Given the file resources.resjson\de-DE\resources.resjson:
-{
- "loc.messages.GoodDay": "Guten Tag!"
-}
-
-The net result from the import command would be one new key-value pair added to the internal dictionary: Key = 'GoodDay', Value = 'Guten Tag!'
-#>
-function Import-LocStrings {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- # Validate the file exists.
- if (!(Test-Path -LiteralPath $LiteralPath -PathType Leaf)) {
- Write-Warning (Get-LocString -Key PSLIB_FileNotFound0 -ArgumentList $LiteralPath)
- return
- }
-
- # Load the json.
- Write-Verbose "Loading resource strings from: $LiteralPath"
- $count = 0
- if ($messages = (Get-Content -LiteralPath $LiteralPath -Encoding UTF8 | Out-String | ConvertFrom-Json).messages) {
- # Add each resource string to the hashtable.
- foreach ($member in (Get-Member -InputObject $messages -MemberType NoteProperty)) {
- [string]$key = $member.Name
- $script:resourceStrings[$key] = $messages."$key"
- $count++
- }
- }
-
- Write-Verbose "Loaded $count strings."
-
- # Get the culture.
- $culture = Get-TaskVariable -Name "System.Culture" -Default "en-US"
-
- # Load the resjson.
- $resjsonPath = "$([System.IO.Path]::GetDirectoryName($LiteralPath))\Strings\resources.resjson\$culture\resources.resjson"
- if (Test-Path -LiteralPath $resjsonPath) {
- Write-Verbose "Loading resource strings from: $resjsonPath"
- $count = 0
- $resjson = Get-Content -LiteralPath $resjsonPath -Encoding UTF8 | Out-String | ConvertFrom-Json
- foreach ($member in (Get-Member -Name loc.messages.* -InputObject $resjson -MemberType NoteProperty)) {
- if (!($value = $resjson."$($member.Name)")) {
- continue
- }
-
- [string]$key = $member.Name.Substring('loc.messages.'.Length)
- $script:resourceStrings[$key] = $value
- $count++
- }
-
- Write-Verbose "Loaded $count strings."
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
deleted file mode 100644
index a8462ef..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/LoggingCommandFunctions.ps1
+++ /dev/null
@@ -1,506 +0,0 @@
-$script:loggingCommandPrefix = '##vso['
-$script:loggingCommandEscapeMappings = @( # TODO: WHAT ABOUT "="? WHAT ABOUT "%"?
- New-Object psobject -Property @{ Token = ';' ; Replacement = '%3B' }
- New-Object psobject -Property @{ Token = "`r" ; Replacement = '%0D' }
- New-Object psobject -Property @{ Token = "`n" ; Replacement = '%0A' }
-)
-# TODO: BUG: Escape ]
-# TODO: BUG: Escape % ???
-# TODO: Add test to verify don't need to escape "=".
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddAttachment {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'addattachment' -Data $Path -Properties @{
- 'type' = $Type
- 'name' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AddBuildTag {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'addbuildtag' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-AssociateArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [hashtable]$Properties,
- [switch]$AsOutput)
-
- $p = @{ }
- if ($Properties) {
- foreach ($key in $Properties.Keys) {
- $p[$key] = $Properties[$key]
- }
- }
-
- $p['artifactname'] = $Name
- $p['artifacttype'] = $Type
- Write-LoggingCommand -Area 'artifact' -Event 'associate' -Data $Path -Properties $p -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-LogDetail {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [guid]$Id,
- $ParentId,
- [string]$Type,
- [string]$Name,
- $Order,
- $StartTime,
- $FinishTime,
- $Progress,
- [ValidateSet('Unknown', 'Initialized', 'InProgress', 'Completed')]
- [Parameter()]
- $State,
- [ValidateSet('Succeeded', 'SucceededWithIssues', 'Failed', 'Cancelled', 'Skipped')]
- [Parameter()]
- $Result,
- [string]$Message,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'logdetail' -Data $Message -Properties @{
- 'id' = $Id
- 'parentid' = $ParentId
- 'type' = $Type
- 'name' = $Name
- 'order' = $Order
- 'starttime' = $StartTime
- 'finishtime' = $FinishTime
- 'progress' = $Progress
- 'state' = $State
- 'result' = $Result
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetProgress {
- [CmdletBinding()]
- param(
- [ValidateRange(0, 100)]
- [Parameter(Mandatory = $true)]
- [int]$Percent,
- [string]$CurrentOperation,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setprogress' -Data $CurrentOperation -Properties @{
- 'value' = $Percent
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetResult {
- [CmdletBinding(DefaultParameterSetName = 'AsOutput')]
- param(
- [ValidateSet("Succeeded", "SucceededWithIssues", "Failed", "Cancelled", "Skipped")]
- [Parameter(Mandatory = $true)]
- [string]$Result,
- [string]$Message,
- [Parameter(ParameterSetName = 'AsOutput')]
- [switch]$AsOutput,
- [Parameter(ParameterSetName = 'DoNotThrow')]
- [switch]$DoNotThrow)
-
- Write-LoggingCommand -Area 'task' -Event 'complete' -Data $Message -Properties @{
- 'result' = $Result
- } -AsOutput:$AsOutput
- if ($Result -eq 'Failed' -and !$AsOutput -and !$DoNotThrow) {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- throw (New-Object VstsTaskSdk.TerminationException($Message))
- }
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetSecret {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setsecret' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-SetVariable {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [string]$Value,
- [switch]$Secret,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'task' -Event 'setvariable' -Data $Value -Properties @{
- 'variable' = $Name
- 'issecret' = $Secret
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskDebug {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskError {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type error @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskVerbose {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsOutput)
-
- Write-TaskDebug_Internal @PSBoundParameters -AsVerbose
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-TaskWarning {
- [CmdletBinding()]
- param(
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- Write-LogIssue -Type warning @PSBoundParameters
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UpdateBuildNumber {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Value,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'updatebuildnumber' -Data $Value -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadArtifact {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$ContainerFolder,
- [Parameter(Mandatory = $true)]
- [string]$Name,
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'artifact' -Event 'upload' -Data $Path -Properties @{
- 'containerfolder' = $ContainerFolder
- 'artifactname' = $Name
- } -AsOutput:$AsOutput
-}
-
-<#
-.SYNOPSIS
-See https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md
-
-.PARAMETER AsOutput
-Indicates whether to write the logging command directly to the host or to the output pipeline.
-#>
-function Write-UploadBuildLog {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path,
- [switch]$AsOutput)
-
- Write-LoggingCommand -Area 'build' -Event 'uploadlog' -Data $Path -AsOutput:$AsOutput
-}
-
-########################################
-# Private functions.
-########################################
-function Format-LoggingCommandData {
- [CmdletBinding()]
- param([string]$Value, [switch]$Reverse)
-
- if (!$Value) {
- return ''
- }
-
- if (!$Reverse) {
- foreach ($mapping in $script:loggingCommandEscapeMappings) {
- $Value = $Value.Replace($mapping.Token, $mapping.Replacement)
- }
- } else {
- for ($i = $script:loggingCommandEscapeMappings.Length - 1 ; $i -ge 0 ; $i--) {
- $mapping = $script:loggingCommandEscapeMappings[$i]
- $Value = $Value.Replace($mapping.Replacement, $mapping.Token)
- }
- }
-
- return $Value
-}
-
-function Format-LoggingCommand {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Area,
- [Parameter(Mandatory = $true)]
- [string]$Event,
- [string]$Data,
- [hashtable]$Properties)
-
- # Append the preamble.
- [System.Text.StringBuilder]$sb = New-Object -TypeName System.Text.StringBuilder
- $null = $sb.Append($script:loggingCommandPrefix).Append($Area).Append('.').Append($Event)
-
- # Append the properties.
- if ($Properties) {
- $first = $true
- foreach ($key in $Properties.Keys) {
- [string]$value = Format-LoggingCommandData $Properties[$key]
- if ($value) {
- if ($first) {
- $null = $sb.Append(' ')
- $first = $false
- } else {
- $null = $sb.Append(';')
- }
-
- $null = $sb.Append("$key=$value")
- }
- }
- }
-
- # Append the tail and output the value.
- $Data = Format-LoggingCommandData $Data
- $sb.Append(']').Append($Data).ToString()
-}
-
-function Write-LoggingCommand {
- [CmdletBinding(DefaultParameterSetName = 'Parameters')]
- param(
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Area,
- [Parameter(Mandatory = $true, ParameterSetName = 'Parameters')]
- [string]$Event,
- [Parameter(ParameterSetName = 'Parameters')]
- [string]$Data,
- [Parameter(ParameterSetName = 'Parameters')]
- [hashtable]$Properties,
- [Parameter(Mandatory = $true, ParameterSetName = 'Object')]
- $Command,
- [switch]$AsOutput)
-
- if ($PSCmdlet.ParameterSetName -eq 'Object') {
- Write-LoggingCommand -Area $Command.Area -Event $Command.Event -Data $Command.Data -Properties $Command.Properties -AsOutput:$AsOutput
- return
- }
-
- $command = Format-LoggingCommand -Area $Area -Event $Event -Data $Data -Properties $Properties
- if ($AsOutput) {
- $command
- } else {
- Write-Host $command
- }
-}
-
-function Write-LogIssue {
- [CmdletBinding()]
- param(
- [ValidateSet('warning', 'error')]
- [Parameter(Mandatory = $true)]
- [string]$Type,
- [string]$Message,
- [string]$ErrCode,
- [string]$SourcePath,
- [string]$LineNumber,
- [string]$ColumnNumber,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'logissue' -Data $Message -Properties @{
- 'type' = $Type
- 'code' = $ErrCode
- 'sourcepath' = $SourcePath
- 'linenumber' = $LineNumber
- 'columnnumber' = $ColumnNumber
- }
- if ($AsOutput) {
- return $command
- }
-
- if ($Type -eq 'error') {
- $foregroundColor = $host.PrivateData.ErrorForegroundColor
- $backgroundColor = $host.PrivateData.ErrorBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Red
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.WarningForegroundColor
- $backgroundColor = $host.PrivateData.WarningBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Yellow
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
-
-function Write-TaskDebug_Internal {
- [CmdletBinding()]
- param(
- [string]$Message,
- [switch]$AsVerbose,
- [switch]$AsOutput)
-
- $command = Format-LoggingCommand -Area 'task' -Event 'debug' -Data $Message
- if ($AsOutput) {
- return $command
- }
-
- if ($AsVerbose) {
- $foregroundColor = $host.PrivateData.VerboseForegroundColor
- $backgroundColor = $host.PrivateData.VerboseBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::Cyan
- $backgroundColor = [System.ConsoleColor]::Black
- }
- } else {
- $foregroundColor = $host.PrivateData.DebugForegroundColor
- $backgroundColor = $host.PrivateData.DebugBackgroundColor
- if ($foregroundColor -isnot [System.ConsoleColor] -or $backgroundColor -isnot [System.ConsoleColor]) {
- $foregroundColor = [System.ConsoleColor]::DarkGray
- $backgroundColor = [System.ConsoleColor]::Black
- }
- }
-
- Write-Host -Object $command -ForegroundColor $foregroundColor -BackgroundColor $backgroundColor
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
deleted file mode 100644
index 51cda34..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/LongPathFunctions.ps1
+++ /dev/null
@@ -1,205 +0,0 @@
-########################################
-# Private functions.
-########################################
-function ConvertFrom-LongFormPath {
- [CmdletBinding()]
- param([string]$Path)
-
- if ($Path) {
- if ($Path.StartsWith('\\?\UNC')) {
- # E.g. \\?\UNC\server\share -> \\server\share
- return $Path.Substring(1, '\?\UNC'.Length)
- } elseif ($Path.StartsWith('\\?\')) {
- # E.g. \\?\C:\directory -> C:\directory
- return $Path.Substring('\\?\'.Length)
- }
- }
-
- return $Path
-}
-function ConvertTo-LongFormPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$longFormPath = Get-FullNormalizedPath -Path $Path
- if ($longFormPath -and !$longFormPath.StartsWith('\\?')) {
- if ($longFormPath.StartsWith('\\')) {
- # E.g. \\server\share -> \\?\UNC\server\share
- return "\\?\UNC$($longFormPath.Substring(1))"
- } else {
- # E.g. C:\directory -> \\?\C:\directory
- return "\\?\$longFormPath"
- }
- }
-
- return $longFormPath
-}
-
-# TODO: ADD A SWITCH TO EXCLUDE FILES, A SWITCH TO EXCLUDE DIRECTORIES, AND A SWITCH NOT TO FOLLOW REPARSE POINTS.
-function Get-DirectoryChildItem {
- [CmdletBinding()]
- param(
- [string]$Path,
- [ValidateNotNullOrEmpty()]
- [Parameter()]
- [string]$Filter = "*",
- [switch]$Force,
- [VstsTaskSdk.FS.FindFlags]$Flags = [VstsTaskSdk.FS.FindFlags]::LargeFetch,
- [VstsTaskSdk.FS.FindInfoLevel]$InfoLevel = [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- [switch]$Recurse)
-
- $stackOfDirectoryQueues = New-Object System.Collections.Stack
- while ($true) {
- $directoryQueue = New-Object System.Collections.Queue
- $fileQueue = New-Object System.Collections.Queue
- $findData = New-Object VstsTaskSdk.FS.FindData
- $longFormPath = (ConvertTo-LongFormPath $Path)
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, $Filter),
- $InfoLevel,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- # Output directories immediately.
- if ($item.Attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- $item
- # Append to the directory queue if recursive and default filter.
- if ($Recurse -and $Filter -eq '*') {
- $directoryQueue.Enqueue($item)
- }
- } else {
- # Hold the files until all directories have been output.
- $fileQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
-
- # If recursive and non-default filter, queue child directories.
- if ($Recurse -and $Filter -ne '*') {
- $findData = New-Object VstsTaskSdk.FS.FindData
- $handle = $null
- try {
- $handle = [VstsTaskSdk.FS.NativeMethods]::FindFirstFileEx(
- [System.IO.Path]::Combine($longFormPath, '*'),
- [VstsTaskSdk.FS.FindInfoLevel]::Basic,
- $findData,
- [VstsTaskSdk.FS.FindSearchOps]::NameMatch,
- [System.IntPtr]::Zero,
- $Flags)
- if (!$handle.IsInvalid) {
- while ($true) {
- if ($findData.fileName -notin '.', '..') {
- $attributes = [VstsTaskSdk.FS.Attributes]$findData.fileAttributes
- # If the item is hidden, check if $Force is specified.
- if ($Force -or !$attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Hidden)) {
- # Collect directories only.
- if ($attributes.HasFlag([VstsTaskSdk.FS.Attributes]::Directory)) {
- # Create the item.
- $item = New-Object -TypeName psobject -Property @{
- 'Attributes' = $attributes
- 'FullName' = (ConvertFrom-LongFormPath -Path ([System.IO.Path]::Combine($Path, $findData.fileName)))
- 'Name' = $findData.fileName
- }
- $directoryQueue.Enqueue($item)
- }
- }
- }
-
- if (!([VstsTaskSdk.FS.NativeMethods]::FindNextFile($handle, $findData))) { break }
-
- if ($handle.IsInvalid) {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- Get-LocString -Key PSLIB_EnumeratingSubdirectoriesFailedForPath0 -ArgumentList $Path
- ))
- }
- }
- }
- } finally {
- if ($handle -ne $null) { $handle.Dispose() }
- }
- }
-
- # Output the files.
- $fileQueue
-
- # Push the directory queue onto the stack if any directories were found.
- if ($directoryQueue.Count) { $stackOfDirectoryQueues.Push($directoryQueue) }
-
- # Break out of the loop if no more directory queues to process.
- if (!$stackOfDirectoryQueues.Count) { break }
-
- # Get the next path.
- $directoryQueue = $stackOfDirectoryQueues.Peek()
- $Path = $directoryQueue.Dequeue().FullName
-
- # Pop the directory queue if it's empty.
- if (!$directoryQueue.Count) { $null = $stackOfDirectoryQueues.Pop() }
- }
-}
-
-function Get-FullNormalizedPath {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$Path)
-
- [string]$outPath = $Path
- [uint32]$bufferSize = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, 0, $null, $null)
- [int]$lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($bufferSize -gt 0) {
- $absolutePath = New-Object System.Text.StringBuilder([int]$bufferSize)
- [uint32]$length = [VstsTaskSdk.FS.NativeMethods]::GetFullPathName($Path, $bufferSize, $absolutePath, $null)
- $lastWin32Error = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()
- if ($length -gt 0) {
- $outPath = $absolutePath.ToString()
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
- } else {
- throw (New-Object -TypeName System.ComponentModel.Win32Exception -ArgumentList @(
- $lastWin32Error
- Get-LocString -Key PSLIB_PathLengthNotReturnedFor0 -ArgumentList $Path
- ))
- }
-
- if ($outPath.EndsWith('\') -and !$outPath.EndsWith(':\')) {
- $outPath = $outPath.TrimEnd('\')
- }
-
- $outPath
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Minimatch.dll b/apimwsdl/v2/ps_modules/VstsTaskSdk/Minimatch.dll
deleted file mode 100644
index 700ddc4..0000000
Binary files a/apimwsdl/v2/ps_modules/VstsTaskSdk/Minimatch.dll and /dev/null differ
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
deleted file mode 100644
index 5ec7f7c..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/OutFunctions.ps1
+++ /dev/null
@@ -1,79 +0,0 @@
-# TODO: It would be better if the Out-Default function resolved the underlying Out-Default
-# command in the begin block. This would allow for supporting other modules that override
-# Out-Default.
-$script:outDefaultCmdlet = $ExecutionContext.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\Out-Default")
-
-########################################
-# Public functions.
-########################################
-function Out-Default {
- [CmdletBinding(ConfirmImpact = "Medium")]
- param(
- [Parameter(ValueFromPipeline = $true)]
- [System.Management.Automation.PSObject]$InputObject)
-
- begin {
- #Write-Host '[Entering Begin Out-Default]'
- $__sp = { & $script:outDefaultCmdlet @PSBoundParameters }.GetSteppablePipeline()
- $__sp.Begin($pscmdlet)
- #Write-Host '[Leaving Begin Out-Default]'
- }
-
- process {
- #Write-Host '[Entering Process Out-Default]'
- if ($_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose -Message 'Error record:' 4>&1 | Out-Default
- Write-Verbose -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647)) 4>&1 | Out-Default
- Write-Verbose -Message 'Script stack trace:' 4>&1 | Out-Default
- Write-Verbose -Message "$($_.ScriptStackTrace)" 4>&1 | Out-Default
- Write-Verbose -Message 'Exception:' 4>&1 | Out-Default
- Write-Verbose -Message $_.Exception.ToString() 4>&1 | Out-Default
- Write-TaskError -Message $_.Exception.Message
- } elseif ($_ -is [System.Management.Automation.WarningRecord]) {
- Write-TaskWarning -Message (Remove-TrailingNewLine (Out-String -InputObject $_ -Width 2147483647))
- } elseif ($_ -is [System.Management.Automation.VerboseRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskVerbose -Message $private:str
- }
- } elseif ($_ -is [System.Management.Automation.DebugRecord] -and !$global:__vstsNoOverrideVerbose) {
- foreach ($private:str in (Format-DebugMessage -Object $_)) {
- Write-TaskDebug -Message $private:str
- }
- } else {
-# TODO: Consider using out-string here to control the width. As a security precaution it would actually be best to set it to max so wrapping doesn't interfere with secret masking.
- $__sp.Process($_)
- }
-
- #Write-Host '[Leaving Process Out-Default]'
- }
-
- end {
- #Write-Host '[Entering End Out-Default]'
- $__sp.End()
- #Write-Host '[Leaving End Out-Default]'
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Format-DebugMessage {
- [CmdletBinding()]
- param([psobject]$Object)
-
- $private:str = Out-String -InputObject $Object -Width 2147483647
- $private:str = Remove-TrailingNewLine $private:str
- "$private:str".Replace("`r`n", "`n").Replace("`r", "`n").Split("`n"[0])
-}
-
-function Remove-TrailingNewLine {
- [CmdletBinding()]
- param($Str)
- if ([object]::ReferenceEquals($Str, $null)) {
- return $Str
- } elseif ($Str.EndsWith("`r`n")) {
- return $Str.Substring(0, $Str.Length - 2)
- } else {
- return $Str
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
deleted file mode 100644
index c0cddc6..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/ServerOMFunctions.ps1
+++ /dev/null
@@ -1,593 +0,0 @@
-<#
-.SYNOPSIS
-Gets assembly reference information.
-
-.DESCRIPTION
-Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK.
-
-Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario.
-
-Walks an assembly's references to determine all of it's dependencies. Also walks the references of the dependencies, and so on until all nested dependencies have been traversed. Dependencies are searched for in the directory of the specified assembly. NET Framework assemblies are omitted.
-
-See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER LiteralPath
-Assembly to walk.
-
-.EXAMPLE
-Get-VstsAssemblyReference -LiteralPath C:\nuget\microsoft.teamfoundationserver.client.14.102.0\lib\net45\Microsoft.TeamFoundation.Build2.WebApi.dll
-#>
-function Get-AssemblyReference {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath)
-
- $ErrorActionPreference = 'Stop'
- Write-Warning "Not supported for use during task exection. This function is only intended to help developers resolve the minimal set of DLLs that need to be bundled when consuming the VSTS REST SDK or TFS Extended Client SDK. The interface and output may change between patch releases of the VSTS Task SDK."
- Write-Output ''
- Write-Warning "Only a subset of the referenced assemblies may actually be required, depending on the functionality used by your task. It is best to bundle only the DLLs required for your scenario."
- $directory = [System.IO.Path]::GetDirectoryName($LiteralPath)
- $hashtable = @{ }
- $queue = @( [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($LiteralPath).GetName() )
- while ($queue.Count) {
- # Add a blank line between assemblies.
- Write-Output ''
-
- # Pop.
- $assemblyName = $queue[0]
- $queue = @( $queue | Select-Object -Skip 1 )
-
- # Attempt to find the assembly in the same directory.
- $assembly = $null
- $path = "$directory\$($assemblyName.Name).dll"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- } else {
- $path = "$directory\$($assemblyName.Name).exe"
- if ((Test-Path -LiteralPath $path -PathType Leaf)) {
- $assembly = [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($path)
- }
- }
-
- # Make sure the assembly full name matches, not just the file name.
- if ($assembly -and $assembly.GetName().FullName -ne $assemblyName.FullName) {
- $assembly = $null
- }
-
- # Print the assembly.
- if ($assembly) {
- Write-Output $assemblyName.FullName
- } else {
- if ($assemblyName.FullName -eq 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed') {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) *** This is an expected condition when using the HTTP clients from the 15.x VSTS REST SDK. Use Get-VstsVssHttpClient to load the HTTP clients (which applies a binding redirect assembly resolver for Newtonsoft.Json). Otherwise you will need to manage the binding redirect yourself."
- } else {
- Write-Warning "*** NOT FOUND $($assemblyName.FullName) ***"
- }
-
- continue
- }
-
- # Walk the references.
- $refAssemblyNames = @( $assembly.GetReferencedAssemblies() )
- for ($i = 0 ; $i -lt $refAssemblyNames.Count ; $i++) {
- $refAssemblyName = $refAssemblyNames[$i]
-
- # Skip framework assemblies.
- $fxPaths = @(
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\$($refAssemblyName.Name).dll"
- "$env:windir\Microsoft.Net\Framework64\v4.0.30319\WPF\$($refAssemblyName.Name).dll"
- )
- $fxPath = $fxPaths |
- Where-Object { Test-Path -LiteralPath $_ -PathType Leaf } |
- Where-Object { [System.Reflection.Assembly]::ReflectionOnlyLoadFrom($_).GetName().FullName -eq $refAssemblyName.FullName }
- if ($fxPath) {
- continue
- }
-
- # Print the reference.
- Write-Output " $($refAssemblyName.FullName)"
-
- # Add new references to the queue.
- if (!$hashtable[$refAssemblyName.FullName]) {
- $queue += $refAssemblyName
- $hashtable[$refAssemblyName.FullName] = $true
- }
- }
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the TFS extended client SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-Refer to Get-VstsTfsService for a more simple to get a TFS service object.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-$credentials = Get-VstsTfsClientCredentials
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.VersionControl.Client.dll"
-$tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection(
- (Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require),
- $credentials)
-$versionControlServer = $tfsTeamProjectCollection.GetService([Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer])
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsClientCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Validate the type can be found.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsClientCredentials' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Construct the credentials.
- $credentials = New-Object Microsoft.TeamFoundation.Client.TfsClientCredentials($false) # Do not use default credentials.
- $credentials.AllowInteractive = $false
- $credentials.Federated = New-Object Microsoft.TeamFoundation.Client.OAuthTokenCredential([string]$endpoint.auth.parameters.AccessToken)
- return $credentials
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a TFS extended client service.
-
-.DESCRIPTION
-Gets an instance of an ITfsTeamProjectCollectionObject.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the service to get.
-
-.PARAMETER OMDirectory
-Directory where the extended client object model DLLs are located. If the DLLs for the types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the TFS extended client SDK from a task.
-
-.PARAMETER Uri
-URI to use when initializing the service. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-.PARAMETER TfsClientCredentials
-Credentials to use when intializing the service. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-.EXAMPLE
-$versionControlServer = Get-VstsTfsService -TypeName Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer
-$versionControlServer.GetItems('$/*').Items | Format-List
-#>
-function Get-TfsService {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $TfsClientCredentials)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Default the credentials.
- if (!$TfsClientCredentials) {
- $TfsClientCredentials = Get-TfsClientCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the project collection type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.TeamFoundation.Client.TfsTeamProjectCollection' -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Load the project collection object.
- $tfsTeamProjectCollection = New-Object Microsoft.TeamFoundation.Client.TfsTeamProjectCollection($Uri, $TfsClientCredentials)
-
- # Validate the requested type can be loaded.
- $type = Get-OMType -TypeName $TypeName -OMKind 'ExtendedClient' -OMDirectory $OMDirectory -Require
-
- # Return the service object.
- return $tfsTeamProjectCollection.GetService($type)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a credentials object that can be used with the VSTS REST SDK.
-
-.DESCRIPTION
-The agent job token is used to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project service build/release identity).
-
-Refer to Get-VstsVssHttpClient for a more simple to get a VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.EXAMPLE
-#
-# Refer to Get-VstsTfsService for a more simple way to get a TFS service object.
-#
-# This example works using the 14.x .NET SDK. A Newtonsoft.Json 6.0 to 8.0 binding
-# redirect may be required when working with the 15.x SDK. Or use Get-VstsVssHttpClient
-# to avoid managing the binding redirect.
-#
-$vssCredentials = Get-VstsVssCredentials
-$collectionUrl = New-Object System.Uri((Get-VstsTaskVariable -Name 'System.TeamFoundationCollectionUri' -Require))
-Add-Type -LiteralPath "$PSScriptRoot\Microsoft.TeamFoundation.Core.WebApi.dll"
-$projectHttpClient = New-Object Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient($collectionUrl, $vssCredentials)
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssCredentials {
- [CmdletBinding()]
- param([string]$OMDirectory)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Get the endpoint.
- $endpoint = Get-Endpoint -Name SystemVssConnection -Require
-
- # Check if the VssOAuthAccessTokenCredential type is available.
- if ((Get-OMType -TypeName 'Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory)) {
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.OAuth.VssOAuthAccessTokenCredential($endpoint.auth.parameters.AccessToken)
- } else {
- # Validate the fallback type can be loaded.
- $null = Get-OMType -TypeName 'Microsoft.VisualStudio.Services.Client.VssOAuthCredential' -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Create the federated credential.
- $federatedCredential = New-Object Microsoft.VisualStudio.Services.Client.VssOAuthCredential($endpoint.auth.parameters.AccessToken)
- }
-
- # Return the credentials.
- return New-Object Microsoft.VisualStudio.Services.Common.VssCredentials(
- (New-Object Microsoft.VisualStudio.Services.Common.WindowsCredential($false)), # Do not use default credentials.
- $federatedCredential,
- [Microsoft.VisualStudio.Services.Common.CredentialPromptType]::DoNotPrompt)
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VSS HTTP client.
-
-.DESCRIPTION
-Gets an instance of an VSS HTTP client.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-.PARAMETER TypeName
-Namespace-qualified type name of the HTTP client to get.
-
-.PARAMETER OMDirectory
-Directory where the REST client object model DLLs are located. If the DLLs for the credential types are not already loaded, an attempt will be made to automatically load the required DLLs from the object model directory.
-
-If not specified, defaults to the directory of the entry script for the task.
-
-*** DO NOT USE Agent.ServerOMDirectory *** See https://github.com/Microsoft/vsts-task-lib/tree/master/powershell/Docs/UsingOM.md for reliable usage when working with the VSTS REST SDK from a task.
-
-# .PARAMETER Uri
-# URI to use when initializing the HTTP client. If not specified, defaults to System.TeamFoundationCollectionUri.
-
-# .PARAMETER VssCredentials
-# Credentials to use when intializing the HTTP client. If not specified, the default uses the agent job token to construct the credentials object. The identity associated with the token depends on the scope selected in the build/release definition (either the project collection build/release service identity, or the project build/release service identity).
-
-# .PARAMETER WebProxy
-# WebProxy to use when intializing the HTTP client. If not specified, the default uses the proxy configuration agent current has.
-
-.EXAMPLE
-$projectHttpClient = Get-VstsVssHttpClient -TypeName Microsoft.TeamFoundation.Core.WebApi.ProjectHttpClient
-$projectHttpClient.GetProjects().Result
-#>
-function Get-VssHttpClient {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [string]$OMDirectory,
-
- [string]$Uri,
-
- $VssCredentials,
-
- $WebProxy = (Get-WebProxy))
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- $originalErrorActionPreference = $ErrorActionPreference
- try {
- $ErrorActionPreference = 'Stop'
-
- # Default the URI to the collection URI.
- if (!$Uri) {
- $Uri = Get-TaskVariable -Name System.TeamFoundationCollectionUri -Require
- }
-
- # Cast the URI.
- [uri]$Uri = New-Object System.Uri($Uri)
-
- # Default the credentials.
- if (!$VssCredentials) {
- $VssCredentials = Get-VssCredentials -OMDirectory $OMDirectory
- }
-
- # Validate the type can be loaded.
- $null = Get-OMType -TypeName $TypeName -OMKind 'WebApi' -OMDirectory $OMDirectory -Require
-
- # Update proxy setting for vss http client
- [Microsoft.VisualStudio.Services.Common.VssHttpMessageHandler]::DefaultWebProxy = $WebProxy
-
- # Try to construct the HTTP client.
- Write-Verbose "Constructing HTTP client."
- try {
- return New-Object $TypeName($Uri, $VssCredentials)
- } catch {
- # Rethrow if the exception is not due to Newtonsoft.Json DLL not found.
- if ($_.Exception.InnerException -isnot [System.IO.FileNotFoundException] -or
- $_.Exception.InnerException.FileName -notlike 'Newtonsoft.Json, *') {
-
- throw
- }
-
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Test if the Newtonsoft.Json DLL exists in the OM directory.
- $newtonsoftDll = [System.IO.Path]::Combine($OMDirectory, "Newtonsoft.Json.dll")
- Write-Verbose "Testing file path: '$newtonsoftDll'"
- if (!(Test-Path -LiteralPath $newtonsoftDll -PathType Leaf)) {
- Write-Verbose 'Not found. Rethrowing exception.'
- throw
- }
-
- # Add a binding redirect and try again. Parts of the Dev15 preview SDK have a
- # dependency on the 6.0.0.0 Newtonsoft.Json DLL, while other parts reference
- # the 8.0.0.0 Newtonsoft.Json DLL.
- Write-Verbose "Adding assembly resolver."
- $onAssemblyResolve = [System.ResolveEventHandler]{
- param($sender, $e)
-
- if ($e.Name -like 'Newtonsoft.Json, *') {
- Write-Verbose "Resolving '$($e.Name)'"
- return [System.Reflection.Assembly]::LoadFrom($newtonsoftDll)
- }
-
- Write-Verbose "Unable to resolve assembly name '$($e.Name)'"
- return $null
- }
- [System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolve)
- try {
- # Try again to construct the HTTP client.
- Write-Verbose "Trying again to construct the HTTP client."
- return New-Object $TypeName($Uri, $VssCredentials)
- } finally {
- # Unregister the assembly resolver.
- Write-Verbose "Removing assemlby resolver."
- [System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolve)
- }
- }
- } catch {
- $ErrorActionPreference = $originalErrorActionPreference
- Write-Error $_
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-<#
-.SYNOPSIS
-Gets a VstsTaskSdk.VstsWebProxy
-
-.DESCRIPTION
-Gets an instance of a VstsTaskSdk.VstsWebProxy that has same proxy configuration as Build/Release agent.
-
-VstsTaskSdk.VstsWebProxy implement System.Net.IWebProxy interface.
-
-.EXAMPLE
-$webProxy = Get-VstsWebProxy
-$webProxy.GetProxy(New-Object System.Uri("https://github.com/Microsoft/vsts-task-lib"))
-#>
-function Get-WebProxy {
- [CmdletBinding()]
- param()
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try
- {
- # Min agent version that supports proxy
- Assert-Agent -Minimum '2.105.7'
-
- $proxyUrl = Get-TaskVariable -Name Agent.ProxyUrl
- $proxyUserName = Get-TaskVariable -Name Agent.ProxyUserName
- $proxyPassword = Get-TaskVariable -Name Agent.ProxyPassword
- $proxyBypassListJson = Get-TaskVariable -Name Agent.ProxyBypassList
- [string[]]$ProxyBypassList = ConvertFrom-Json -InputObject $ProxyBypassListJson
-
- return New-Object -TypeName VstsTaskSdk.VstsWebProxy -ArgumentList @($proxyUrl, $proxyUserName, $proxyPassword, $proxyBypassList)
- }
- finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-OMType {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$TypeName,
-
- [ValidateSet('ExtendedClient', 'WebApi')]
- [Parameter(Mandatory = $true)]
- [string]$OMKind,
-
- [string]$OMDirectory,
-
- [switch]$Require)
-
- Trace-EnteringInvocation -InvocationInfo $MyInvocation
- try {
- # Default the OMDirectory to the directory of the entry script for the task.
- if (!$OMDirectory) {
- $OMDirectory = [System.IO.Path]::GetFullPath("$PSScriptRoot\..\..")
- Write-Verbose "Defaulted OM directory to: '$OMDirectory'"
- }
-
- # Try to load the type.
- $errorRecord = $null
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- # Store the error record.
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
-
- # Build a list of candidate DLL file paths from the namespace.
- $dllPaths = @( )
- $namespace = $TypeName
- while ($namespace.LastIndexOf('.') -gt 0) {
- # Trim the next segment from the namespace.
- $namespace = $namespace.SubString(0, $namespace.LastIndexOf('.'))
-
- # Derive potential DLL file paths based on the namespace and OM kind (i.e. extended client vs web API).
- if ($OMKind -eq 'ExtendedClient') {
- if ($namespace -like 'Microsoft.TeamFoundation.*') {
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- } else {
- if ($namespace -like 'Microsoft.TeamFoundation.*' -or
- $namespace -like 'Microsoft.VisualStudio.Services' -or
- $namespace -like 'Microsoft.VisualStudio.Services.*') {
-
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.WebApi.dll")
- $dllPaths += [System.IO.Path]::Combine($OMDirectory, "$namespace.dll")
- }
- }
- }
-
- foreach ($dllPath in $dllPaths) {
- # Check whether the DLL exists.
- Write-Verbose "Testing leaf path: '$dllPath'"
- if (!(Test-Path -PathType Leaf -LiteralPath "$dllPath")) {
- Write-Verbose "Not found."
- continue
- }
-
- # Load the DLL.
- Write-Verbose "Loading assembly: $dllPath"
- try {
- Add-Type -LiteralPath $dllPath
- } catch {
- # Write the information to the verbose stream and proceed to attempt to load the requested type.
- #
- # The requested type may successfully load now. For example, the type used with the 14.0 Web API for the
- # federated credential (VssOAuthCredential) resides in Microsoft.VisualStudio.Services.Client.dll. Even
- # though loading the DLL results in a ReflectionTypeLoadException when Microsoft.ServiceBus.dll (approx 3.75mb)
- # is not present, enough types are loaded to use the VssOAuthCredential federated credential with the Web API
- # HTTP clients.
- Write-Verbose "$($_.Exception.GetType().FullName): $($_.Exception.Message)"
- if ($_.Exception -is [System.Reflection.ReflectionTypeLoadException]) {
- for ($i = 0 ; $i -lt $_.Exception.LoaderExceptions.Length ; $i++) {
- $loaderException = $_.Exception.LoaderExceptions[$i]
- Write-Verbose "LoaderExceptions[$i]: $($loaderException.GetType().FullName): $($loaderException.Message)"
- }
- }
- }
-
- # Try to load the type.
- Write-Verbose "Testing whether type can be loaded: '$TypeName'"
- $ErrorActionPreference = 'Ignore'
- try {
- # Failure when attempting to cast a string to a type, transfers control to the
- # catch handler even when the error action preference is ignore. The error action
- # is set to Ignore so the $Error variable is not polluted.
- $type = [type]$TypeName
-
- # Success.
- Write-Verbose "The type was loaded successfully."
- return $type
- } catch {
- $errorRecord = $_
- }
-
- $ErrorActionPreference = 'Stop'
- Write-Verbose "The type was not loaded."
- }
-
- # Check whether to propagate the error.
- if ($Require) {
- Write-Error $errorRecord
- }
- } finally {
- Trace-LeavingInvocation -InvocationInfo $MyInvocation
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
deleted file mode 100644
index ec97e9b..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/de-de/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Der Containerpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "\"{0}\"-Dienstendpunkt-Anmeldeinformationen",
- "loc.messages.PSLIB_EndpointUrl0": "\"{0}\"-Dienstendpunkt-URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Fehler beim Aufzählen von Unterverzeichnissen für den folgenden Pfad: \"{0}\"",
- "loc.messages.PSLIB_FileNotFound0": "Die Datei wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Input0": "\"{0}\"-Eingabe",
- "loc.messages.PSLIB_InvalidPattern0": "Ungültiges Muster: \"{0}\"",
- "loc.messages.PSLIB_LeafPathNotFound0": "Der Blattpfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Fehler bei der Normalisierung bzw. Erweiterung des Pfads. Die Pfadlänge wurde vom Kernel32-Subsystem nicht zurückgegeben für: \"{0}\"",
- "loc.messages.PSLIB_PathNotFound0": "Der Pfad wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Der Prozess \"{0}\" wurde mit dem Code \"{1}\" beendet.",
- "loc.messages.PSLIB_Required0": "Erforderlich: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Fehler beim Zeichenfolgenformat.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Der Zeichenfolgen-Ressourcenschlüssel wurde nicht gefunden: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "\"{0}\"-Taskvariable"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
deleted file mode 100644
index 66c17bc..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/en-US/resources.resjson
+++ /dev/null
@@ -1,18 +0,0 @@
-{
- "loc.messages.PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "loc.messages.PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "File not found: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' input",
- "loc.messages.PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Path not found: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "loc.messages.PSLIB_Required0": "Required: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "String format failed.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' task variable"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
deleted file mode 100644
index d09d96c..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/es-es/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "No se encuentra la ruta de acceso del contenedor: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenciales del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL del punto de conexión de servicio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "No se pudieron enumerar los subdirectorios de la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Archivo no encontrado: '{0}'",
- "loc.messages.PSLIB_Input0": "Entrada '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Patrón no válido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "No se encuentra la ruta de acceso de la hoja: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "No se pudo normalizar o expandir la ruta de acceso. El subsistema Kernel32 no devolvió la longitud de la ruta de acceso para: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "No se encuentra la ruta de acceso: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "El proceso '{0}' finalizó con el código '{1}'.",
- "loc.messages.PSLIB_Required0": "Se requiere: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Error de formato de cadena.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "No se encuentra la clave de recurso de la cadena: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tarea '{0}'"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
deleted file mode 100644
index 6606ddd..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/fr-fr/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Le chemin du conteneur est introuvable : '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Informations d'identification du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL du point de terminaison de service '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Échec de l'énumération des sous-répertoires pour le chemin : '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "Fichier introuvable : {0}.",
- "loc.messages.PSLIB_Input0": "Entrée '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Modèle non valide : '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Le chemin feuille est introuvable : '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Échec de la normalisation/l'expansion du chemin. La longueur du chemin n'a pas été retournée par le sous-système Kernel32 pour : '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Chemin introuvable : '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Le processus '{0}' s'est arrêté avec le code '{1}'.",
- "loc.messages.PSLIB_Required0": "Obligatoire : {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Échec du format de la chaîne.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Clé de la ressource de type chaîne introuvable : '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variable de tâche '{0}'"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
deleted file mode 100644
index 0b54d99..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/it-IT/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Percorso del contenitore non trovato: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "Credenziali dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EndpointUrl0": "URL dell'endpoint servizio '{0}'",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "L'enumerazione delle sottodirectory per il percorso '{0}' non è riuscita",
- "loc.messages.PSLIB_FileNotFound0": "File non trovato: '{0}'",
- "loc.messages.PSLIB_Input0": "Input di '{0}'",
- "loc.messages.PSLIB_InvalidPattern0": "Criterio non valido: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Percorso foglia non trovato: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "La normalizzazione o l'espansione del percorso non è riuscita. Il sottosistema Kernel32 non ha restituito la lunghezza del percorso per '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "Percorso non trovato: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Il processo '{0}' è stato terminato ed è stato restituito il codice '{1}'.",
- "loc.messages.PSLIB_Required0": "Obbligatorio: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Errore nel formato della stringa.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "La chiave della risorsa stringa non è stata trovata: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "Variabile dell'attività '{0}'"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
deleted file mode 100644
index b0e2bdf..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ja-jp/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "コンテナーのパスが見つかりません: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' サービス エンドポイントの資格情報",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' サービス エンドポイントの URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "パス '{0}' のサブディレクトリを列挙できませんでした",
- "loc.messages.PSLIB_FileNotFound0": "ファイルが見つかりません: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 入力",
- "loc.messages.PSLIB_InvalidPattern0": "使用できないパターンです: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "リーフ パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "パスの正規化/展開に失敗しました。Kernel32 サブシステムからパス '{0}' の長さが返されませんでした",
- "loc.messages.PSLIB_PathNotFound0": "パスが見つかりません: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "プロセス '{0}' がコード '{1}' で終了しました。",
- "loc.messages.PSLIB_Required0": "必要: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "文字列のフォーマットに失敗しました。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "文字列のリソース キーが見つかりません: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' タスク変数"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
deleted file mode 100644
index 60df35b..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ko-KR/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "컨테이너 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 서비스 끝점 자격 증명",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 서비스 끝점 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "경로에 대해 하위 디렉터리를 열거하지 못함: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "{0} 파일을 찾을 수 없습니다.",
- "loc.messages.PSLIB_Input0": "'{0}' 입력",
- "loc.messages.PSLIB_InvalidPattern0": "잘못된 패턴: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "Leaf 경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "경로 정규화/확장에 실패했습니다. 다음에 대해 Kernel32 subsystem에서 경로 길이를 반환하지 않음: '{0}'",
- "loc.messages.PSLIB_PathNotFound0": "경로를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "'{1}' 코드로 '{0}' 프로세스가 종료되었습니다.",
- "loc.messages.PSLIB_Required0": "필수: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "문자열을 포맷하지 못했습니다.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "문자열 리소스 키를 찾을 수 없음: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 작업 변수"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
deleted file mode 100644
index 2d42208..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/ru-RU/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "Путь к контейнеру не найден: \"{0}\".",
- "loc.messages.PSLIB_EndpointAuth0": "Учетные данные конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EndpointUrl0": "URL-адрес конечной точки службы \"{0}\"",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Сбой перечисления подкаталогов для пути: \"{0}\".",
- "loc.messages.PSLIB_FileNotFound0": "Файл не найден: \"{0}\".",
- "loc.messages.PSLIB_Input0": "Входные данные \"{0}\".",
- "loc.messages.PSLIB_InvalidPattern0": "Недопустимый шаблон: \"{0}\".",
- "loc.messages.PSLIB_LeafPathNotFound0": "Путь к конечному объекту не найден: \"{0}\".",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "Сбой нормализации и расширения пути. Длина пути не была возвращена подсистемой Kernel32 для: \"{0}\".",
- "loc.messages.PSLIB_PathNotFound0": "Путь не найден: \"{0}\".",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "Процесс \"{0}\" завершил работу с кодом \"{1}\".",
- "loc.messages.PSLIB_Required0": "Требуется: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "Сбой формата строки.",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "Ключ ресурса строки не найден: \"{0}\".",
- "loc.messages.PSLIB_TaskVariable0": "Переменная задачи \"{0}\""
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
deleted file mode 100644
index 80adce2..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-CN/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路径:“{0}”",
- "loc.messages.PSLIB_EndpointAuth0": "“{0}”服务终结点凭据",
- "loc.messages.PSLIB_EndpointUrl0": "“{0}”服务终结点 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "枚举路径的子目录失败:“{0}”",
- "loc.messages.PSLIB_FileNotFound0": "找不到文件: {0}。",
- "loc.messages.PSLIB_Input0": "“{0}”输入",
- "loc.messages.PSLIB_InvalidPattern0": "无效的模式:“{0}”",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到叶路径:“{0}”",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路径规范化/扩展失败。路径长度不是由“{0}”的 Kernel32 子系统返回的",
- "loc.messages.PSLIB_PathNotFound0": "找不到路径:“{0}”",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "过程“{0}”已退出,代码为“{1}”。",
- "loc.messages.PSLIB_Required0": "必需: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字符串格式无效。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字符串资源关键字:“{0}”",
- "loc.messages.PSLIB_TaskVariable0": "“{0}”任务变量"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson b/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
deleted file mode 100644
index d6a041c..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/Strings/resources.resjson/zh-TW/resources.resjson
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "loc.messages.PSLIB_ContainerPathNotFound0": "找不到容器路徑: '{0}'",
- "loc.messages.PSLIB_EndpointAuth0": "'{0}' 服務端點認證",
- "loc.messages.PSLIB_EndpointUrl0": "'{0}' 服務端點 URL",
- "loc.messages.PSLIB_EnumeratingSubdirectoriesFailedForPath0": "為路徑列舉子目錄失敗: '{0}'",
- "loc.messages.PSLIB_FileNotFound0": "找不到檔案: '{0}'",
- "loc.messages.PSLIB_Input0": "'{0}' 輸入",
- "loc.messages.PSLIB_InvalidPattern0": "模式無效: '{0}'",
- "loc.messages.PSLIB_LeafPathNotFound0": "找不到分葉路徑: '{0}'",
- "loc.messages.PSLIB_PathLengthNotReturnedFor0": "路徑正規化/展開失敗。Kernel32 子系統未傳回 '{0}' 的路徑長度",
- "loc.messages.PSLIB_PathNotFound0": "找不到路徑: '{0}'",
- "loc.messages.PSLIB_Process0ExitedWithCode1": "處理序 '{0}' 以返回碼 '{1}' 結束。",
- "loc.messages.PSLIB_Required0": "必要項: {0}",
- "loc.messages.PSLIB_StringFormatFailed": "字串格式失敗。",
- "loc.messages.PSLIB_StringResourceKeyNotFound0": "找不到字串資源索引鍵: '{0}'",
- "loc.messages.PSLIB_TaskVariable0": "'{0}' 工作變數"
-}
\ No newline at end of file
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
deleted file mode 100644
index 7e62ebd..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/ToolFunctions.ps1
+++ /dev/null
@@ -1,123 +0,0 @@
-<#
-.SYNOPSIS
-Asserts the agent version is at least the specified minimum.
-
-.PARAMETER Minimum
-Minimum version - must be 2.104.1 or higher.
-#>
-function Assert-Agent {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [version]$Minimum)
-
- if (([version]'2.104.1').CompareTo($Minimum) -ge 1) {
- Write-Error "Assert-Agent requires the parameter to be 2.104.1 or higher."
- return
- }
-
- $agent = Get-TaskVariable -Name 'agent.version'
- if (!$agent -or $Minimum.CompareTo([version]$agent) -ge 1) {
- Write-Error (Get-LocString -Key 'PSLIB_AgentVersion0Required' -ArgumentList $Minimum)
- }
-}
-
-<#
-.SYNOPSIS
-Asserts that a path exists. Throws if the path does not exist.
-
-.PARAMETER PassThru
-True to return the path.
-#>
-function Assert-Path {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [string]$LiteralPath,
- [Microsoft.PowerShell.Commands.TestPathType]$PathType = [Microsoft.PowerShell.Commands.TestPathType]::Any,
- [switch]$PassThru)
-
- if ($PathType -eq [Microsoft.PowerShell.Commands.TestPathType]::Any) {
- Write-Verbose "Asserting path exists: '$LiteralPath'"
- } else {
- Write-Verbose "Asserting $("$PathType".ToLowerInvariant()) path exists: '$LiteralPath'"
- }
-
- if (Test-Path -LiteralPath $LiteralPath -PathType $PathType) {
- if ($PassThru) {
- return $LiteralPath
- }
-
- return
- }
-
- $resourceKey = switch ($PathType) {
- ([Microsoft.PowerShell.Commands.TestPathType]::Container) { "PSLIB_ContainerPathNotFound0" ; break }
- ([Microsoft.PowerShell.Commands.TestPathType]::Leaf) { "PSLIB_LeafPathNotFound0" ; break }
- default { "PSLIB_PathNotFound0" }
- }
-
- throw (Get-LocString -Key $resourceKey -ArgumentList $LiteralPath)
-}
-
-<#
-.SYNOPSIS
-Executes an external program.
-
-.DESCRIPTION
-Executes an external program and waits for the process to exit.
-
-After calling this command, the exit code of the process can be retrieved from the variable $LASTEXITCODE.
-
-.PARAMETER Encoding
-This parameter not required for most scenarios. Indicates how to interpret the encoding from the external program. An example use case would be if an external program outputs UTF-16 XML and the output needs to be parsed.
-
-.PARAMETER RequireExitCodeZero
-Indicates whether to write an error to the error pipeline if the exit code is not zero.
-#>
-function Invoke-Tool { # TODO: RENAME TO INVOKE-PROCESS?
- [CmdletBinding()]
- param(
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter(Mandatory = $true)]
- [string]$FileName,
- [ValidatePattern('^[^\r\n]*$')]
- [Parameter()]
- [string]$Arguments,
- [string]$WorkingDirectory,
- [System.Text.Encoding]$Encoding,
- [switch]$RequireExitCodeZero)
-
- Trace-EnteringInvocation $MyInvocation
- $isPushed = $false
- $originalEncoding = $null
- try {
- if ($Encoding) {
- $originalEncoding = [System.Console]::OutputEncoding
- [System.Console]::OutputEncoding = $Encoding
- }
-
- if ($WorkingDirectory) {
- Push-Location -LiteralPath $WorkingDirectory -ErrorAction Stop
- $isPushed = $true
- }
-
- $FileName = $FileName.Replace('"', '').Replace("'", "''")
- Write-Host "##[command]""$FileName"" $Arguments"
- Invoke-Expression "& '$FileName' --% $Arguments"
- Write-Verbose "Exit code: $LASTEXITCODE"
- if ($RequireExitCodeZero -and $LASTEXITCODE -ne 0) {
- Write-Error (Get-LocString -Key PSLIB_Process0ExitedWithCode1 -ArgumentList ([System.IO.Path]::GetFileName($FileName)), $LASTEXITCODE)
- }
- } finally {
- if ($originalEncoding) {
- [System.Console]::OutputEncoding = $originalEncoding
- }
-
- if ($isPushed) {
- Pop-Location
- }
-
- Trace-LeavingInvocation $MyInvocation
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
deleted file mode 100644
index cdbd779..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/TraceFunctions.ps1
+++ /dev/null
@@ -1,139 +0,0 @@
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being entered.
-
-.DESCRIPTION
-Used to trace verbose information when entering a function/script. Writes an entering message followed by a short description of the invocation. Additionally each bound parameter and unbound argument is also traced.
-
-.PARAMETER Parameter
-Wildcard pattern to control which bound parameters are traced.
-#>
-function Trace-EnteringInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo,
- [string[]]$Parameter = '*')
-
- Write-Verbose "Entering $(Get-InvocationDescription $InvocationInfo)."
- $OFS = ", "
- if ($InvocationInfo.BoundParameters.Count -and $Parameter.Count) {
- if ($Parameter.Count -eq 1 -and $Parameter[0] -eq '*') {
- # Trace all parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- }
- } else {
- # Trace matching parameters.
- foreach ($key in $InvocationInfo.BoundParameters.Keys) {
- foreach ($p in $Parameter) {
- if ($key -like $p) {
- Write-Verbose " $($key): '$($InvocationInfo.BoundParameters[$key])'"
- break
- }
- }
- }
- }
- }
-
- # Trace all unbound arguments.
- if (@($InvocationInfo.UnboundArguments).Count) {
- for ($i = 0 ; $i -lt $InvocationInfo.UnboundArguments.Count ; $i++) {
- Write-Verbose " args[$i]: '$($InvocationInfo.UnboundArguments[$i])'"
- }
- }
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about the invocation being left.
-
-.DESCRIPTION
-Used to trace verbose information when leaving a function/script. Writes a leaving message followed by a short description of the invocation.
-#>
-function Trace-LeavingInvocation {
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- Write-Verbose "Leaving $(Get-InvocationDescription $InvocationInfo)."
-}
-
-<#
-.SYNOPSIS
-Writes verbose information about paths.
-
-.DESCRIPTION
-Writes verbose information about the paths. The paths are sorted and a the common root is written only once, followed by each relative path.
-
-.PARAMETER PassThru
-Indicates whether to return the sorted paths.
-#>
-function Trace-Path {
- [CmdletBinding()]
- param(
- [string[]]$Path,
- [switch]$PassThru)
-
- if ($Path.Count -eq 0) {
- Write-Verbose "No paths."
- if ($PassThru) {
- $Path
- }
- } elseif ($Path.Count -eq 1) {
- Write-Verbose "Path: $($Path[0])"
- if ($PassThru) {
- $Path
- }
- } else {
- # Find the greatest common root.
- $sorted = $Path | Sort-Object
- $firstPath = $sorted[0].ToCharArray()
- $lastPath = $sorted[-1].ToCharArray()
- $commonEndIndex = 0
- $j = if ($firstPath.Length -lt $lastPath.Length) { $firstPath.Length } else { $lastPath.Length }
- for ($i = 0 ; $i -lt $j ; $i++) {
- if ($firstPath[$i] -eq $lastPath[$i]) {
- if ($firstPath[$i] -eq '\') {
- $commonEndIndex = $i
- }
- } else {
- break
- }
- }
-
- if ($commonEndIndex -eq 0) {
- # No common root.
- Write-Verbose "Paths:"
- foreach ($p in $sorted) {
- Write-Verbose " $p"
- }
- } else {
- Write-Verbose "Paths: $($Path[0].Substring(0, $commonEndIndex + 1))"
- foreach ($p in $sorted) {
- Write-Verbose " $($p.Substring($commonEndIndex + 1))"
- }
- }
-
- if ($PassThru) {
- $sorted
- }
- }
-}
-
-########################################
-# Private functions.
-########################################
-function Get-InvocationDescription {
- [CmdletBinding()]
- param([System.Management.Automation.InvocationInfo]$InvocationInfo)
-
- if ($InvocationInfo.MyCommand.Path) {
- $InvocationInfo.MyCommand.Path
- } elseif ($InvocationInfo.MyCommand.Name) {
- $InvocationInfo.MyCommand.Name
- } else {
- $InvocationInfo.MyCommand.CommandType
- }
-}
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll b/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll
deleted file mode 100644
index 9d4de16..0000000
Binary files a/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.dll and /dev/null differ
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1
deleted file mode 100644
index e219bf5..0000000
Binary files a/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psd1 and /dev/null differ
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1 b/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
deleted file mode 100644
index e6a5058..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/VstsTaskSdk.psm1
+++ /dev/null
@@ -1,159 +0,0 @@
-[CmdletBinding()]
-param(
- [ValidateNotNull()]
- [Parameter()]
- [hashtable]$ModuleParameters = @{ })
-
-if ($host.Name -ne 'ConsoleHost') {
- Write-Warning "VstsTaskSdk is designed for use with powershell.exe (ConsoleHost). Output may be different when used with other hosts."
-}
-
-# Private module variables.
-[bool]$script:nonInteractive = "$($ModuleParameters['NonInteractive'])" -eq 'true'
-Write-Verbose "NonInteractive: $script:nonInteractive"
-
-# VstsTaskSdk.dll contains the TerminationException and NativeMethods for handle long path
-# We used to do inline C# in this powershell module
-# However when csc compile the inline C#, it will hit process env block size limit since it's not use unicode to encode env
-# To solve the env block size problem, we choose to put all inline C# into an assembly VstsTaskSdk.dll, signing it, package with the PS modules.
-Write-Verbose "Loading compiled helper $PSScriptRoot\VstsTaskSdk.dll."
-Add-Type -LiteralPath $PSScriptRoot\VstsTaskSdk.dll
-
-# Import/export functions.
-. "$PSScriptRoot\FindFunctions.ps1"
-. "$PSScriptRoot\InputFunctions.ps1"
-. "$PSScriptRoot\LegacyFindFunctions.ps1"
-. "$PSScriptRoot\LocalizationFunctions.ps1"
-. "$PSScriptRoot\LoggingCommandFunctions.ps1"
-. "$PSScriptRoot\LongPathFunctions.ps1"
-. "$PSScriptRoot\ServerOMFunctions.ps1"
-. "$PSScriptRoot\ToolFunctions.ps1"
-. "$PSScriptRoot\TraceFunctions.ps1"
-. "$PSScriptRoot\OutFunctions.ps1" # Load the out functions after all of the other functions are loaded.
-Export-ModuleMember -Function @(
- # Find functions.
- 'Find-Match'
- 'New-FindOptions'
- 'New-MatchOptions'
- 'Select-Match'
- # Input functions.
- 'Get-Endpoint'
- 'Get-Input'
- 'Get-TaskVariable'
- 'Get-TaskVariableInfo'
- 'Set-TaskVariable'
- # Legacy find functions.
- 'Find-Files'
- # Localization functions.
- 'Get-LocString'
- 'Import-LocStrings'
- # Logging command functions.
- 'Write-AddAttachment'
- 'Write-AddBuildTag'
- 'Write-AssociateArtifact'
- 'Write-LogDetail'
- 'Write-SetProgress'
- 'Write-SetResult'
- 'Write-SetSecret'
- 'Write-SetVariable'
- 'Write-TaskDebug'
- 'Write-TaskError'
- 'Write-TaskVerbose'
- 'Write-TaskWarning'
- 'Write-UpdateBuildNumber'
- 'Write-UploadArtifact'
- 'Write-UploadBuildLog'
- # Out functions.
- 'Out-Default'
- # Server OM functions.
- 'Get-AssemblyReference'
- 'Get-TfsClientCredentials'
- 'Get-TfsService'
- 'Get-VssCredentials'
- 'Get-VssHttpClient'
- # Tool functions.
- 'Assert-Agent'
- 'Assert-Path'
- 'Invoke-Tool'
- # Trace functions.
- 'Trace-EnteringInvocation'
- 'Trace-LeavingInvocation'
- 'Trace-Path'
- # Proxy functions
- 'Get-WebProxy'
- )
-
-# Override Out-Default globally.
-$null = New-Item -Force -Path "function:\global:Out-Default" -Value (Get-Command -CommandType Function -Name Out-Default -ListImported)
-New-Alias -Name Out-Default -Value "global:Out-Default" -Scope global
-
-# Perform some initialization in a script block to enable merging the pipelines.
-$scriptText = @"
-# Load the SDK resource strings.
-Import-LocStrings "$PSScriptRoot\lib.json"
-
-# Load the module that contains ConvertTo-SecureString.
-if (!(Get-Module -Name Microsoft.PowerShell.Security)) {
- Write-Verbose "Importing the module 'Microsoft.PowerShell.Security'."
- Import-Module -Name Microsoft.PowerShell.Security 2>&1 |
- ForEach-Object {
- if (`$_ -is [System.Management.Automation.ErrorRecord]) {
- Write-Verbose `$_.Exception.Message
- } else {
- ,`$_
- }
- }
-}
-"@
-. ([scriptblock]::Create($scriptText)) 2>&1 3>&1 4>&1 5>&1 | Out-Default
-
-# Create Invoke-VstsTaskScript in a special way so it is not bound to the module.
-# Otherwise calling the task script block would run within the module context.
-#
-# An alternative way to solve the problem is to close the script block (i.e. closure).
-# However, that introduces a different problem. Closed script blocks are created within
-# a dynamic module. Each module gets it's own session state separate from the global
-# session state. When running in a regular script context, Import-Module calls import
-# the target module into the global session state. When running in a module context,
-# Import-Module calls import the target module into the caller module's session state.
-#
-# The goal of a task may include executing ad-hoc scripts. Therefore, task scripts
-# should run in regular script context. The end user specifying an ad-hoc script expects
-# the module import rules to be consistent with the default behavior (i.e. imported
-# into the global session state).
-$null = New-Item -Force -Path "function:\global:Invoke-VstsTaskScript" -Value ([scriptblock]::Create(@'
- [CmdletBinding()]
- param(
- [Parameter(Mandatory = $true)]
- [scriptblock]$ScriptBlock)
-
- try {
- $global:ErrorActionPreference = 'Stop'
-
- # Initialize the environment.
- $vstsModule = Get-Module -Name VstsTaskSdk
- Write-Verbose "$($vstsModule.Name) $($vstsModule.Version) commit $($vstsModule.PrivateData.PSData.CommitHash)" 4>&1 | Out-Default
- & $vstsModule Initialize-Inputs 4>&1 | Out-Default
-
- # Remove the local variable before calling the user's script.
- Remove-Variable -Name vstsModule
-
- # Call the user's script.
- $ScriptBlock |
- ForEach-Object {
- # Remove the scriptblock variable before calling it.
- Remove-Variable -Name ScriptBlock
- & $_ 2>&1 3>&1 4>&1 5>&1 | Out-Default
- }
- } catch [VstsTaskSdk.TerminationException] {
- # Special internal exception type to control the flow. Not currently intended
- # for public usage and subject to change.
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Task script terminated." 4>&1 | Out-Default
- } catch {
- $global:__vstsNoOverrideVerbose = ''
- Write-Verbose "Caught exception from task script." 4>&1 | Out-Default
- $_ | Out-Default
- Write-Host "##vso[task.complete result=Failed]"
- }
-'@))
diff --git a/apimwsdl/v2/ps_modules/VstsTaskSdk/lib.json b/apimwsdl/v2/ps_modules/VstsTaskSdk/lib.json
deleted file mode 100644
index 0cde160..0000000
--- a/apimwsdl/v2/ps_modules/VstsTaskSdk/lib.json
+++ /dev/null
@@ -1,20 +0,0 @@
-{
- "messages": {
- "PSLIB_AgentVersion0Required": "Agent version {0} or higher is required.",
- "PSLIB_ContainerPathNotFound0": "Container path not found: '{0}'",
- "PSLIB_EndpointAuth0": "'{0}' service endpoint credentials",
- "PSLIB_EndpointUrl0": "'{0}' service endpoint URL",
- "PSLIB_EnumeratingSubdirectoriesFailedForPath0": "Enumerating subdirectories failed for path: '{0}'",
- "PSLIB_FileNotFound0": "File not found: '{0}'",
- "PSLIB_Input0": "'{0}' input",
- "PSLIB_InvalidPattern0": "Invalid pattern: '{0}'",
- "PSLIB_LeafPathNotFound0": "Leaf path not found: '{0}'",
- "PSLIB_PathLengthNotReturnedFor0": "Path normalization/expansion failed. The path length was not returned by the Kernel32 subsystem for: '{0}'",
- "PSLIB_PathNotFound0": "Path not found: '{0}'",
- "PSLIB_Process0ExitedWithCode1": "Process '{0}' exited with code '{1}'.",
- "PSLIB_Required0": "Required: {0}",
- "PSLIB_StringFormatFailed": "String format failed.",
- "PSLIB_StringResourceKeyNotFound0": "String resource key not found: '{0}'",
- "PSLIB_TaskVariable0": "'{0}' task variable"
- }
-}
diff --git a/apimwsdl/v2/task.json b/apimwsdl/v2/task.json
deleted file mode 100644
index 1e004d6..0000000
--- a/apimwsdl/v2/task.json
+++ /dev/null
@@ -1,283 +0,0 @@
-{
- "id": "9bfd810a-5e2b-4871-95d8-ae6e677d4224",
- "name": "apimwsdl",
- "friendlyName": "API Management - Create or Update API from WSDL",
- "description": "API Management - Create or update API from WSDL",
- "author": "Stephane Eyskens",
- "helpMarkDown": "API Management - Create/Update API from WSDL",
- "category": "Utility",
- "visibility": [
- "Release"
- ],
- "demands": [],
- "version": {
- "Major": "2",
- "Minor": "1",
- "Patch": "1"
- },
- "minimumAgentVersion": "1.95.0",
- "instanceNameFormat": "API Management - Create/Update API from WSDL $(message)",
- "inputs": [
- {
- "name": "ConnectedServiceNameARM",
- "type": "connectedService:AzureRM",
- "label": "Azure Subscription",
- "defaultValue": "",
- "required": true,
- "helpMarkDown": "Azure Resource Manager subscription to configure before running PowerShell"
-
- },
- {
- "name": "ResourceGroupName",
- "label": "Resource Group",
- "type": "pickList",
- "required": true,
- "helpMarkDown": "Select resource group which contains the API portal",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "ApiPortalName",
- "type": "pickList",
- "label": "API Portal",
- "required": true,
- "helpMarkDown": "The API Portal you want to deploy against",
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "UseProductCreatedByPreviousTask",
- "type": "boolean",
- "label": "Product created by previous task",
- "helpMarkDown": "Make sure the task that creates/updates the product is not disabled and that it is executed by the same agent."
- },
- {
- "name": "product1",
- "type": "multiline",
- "label": "Product(s)",
- "required": true,
- "helpMarkDown": "Product(s) you want to add the API to. One product per line.",
- "properties": {
- "EditableOptions": "True"
- },
- "visibleRule": "UseProductCreatedByPreviousTask=false"
- },
- {
- "name": "soapApiType",
- "type": "pickList",
- "label": "Type of Api to create",
- "required": true,
- "helpMarkDown": "Type of Api to create.",
- "defaultValue": "soap",
- "options": {
- "soap":"SOAP pass-through API",
- "http": "SOAP to REST API"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "wsdllocation",
- "type": "string",
- "label": "WSDL Location URL",
- "required": true,
- "helpMarkDown": "Make sure the URL is connectable from the build servers",
- "defaultValue": ""
- },
- {
- "name": "wsdlServiceName",
- "type": "string",
- "label": "Service Name",
- "required": true,
- "helpMarkDown": "Name of the service as described in the WSDL",
- "defaultValue": ""
- },
- {
- "name": "wsdlEndpointName",
- "type": "string",
- "label": "Service Endpoint",
- "required": true,
- "helpMarkDown": "Name of endpoint(port) to import from WSDL.",
- "defaultValue": ""
- },
- {
- "name": "targetapi",
- "type": "string",
- "label": "API Name",
- "required": true,
- "helpMarkDown": "New or existing API"
- },
- {
- "name": "Description",
- "type": "multiLine",
- "label": "Description",
- "helpMarkDown": "Description appearing to subscribers",
- "required": true
- },
- {
- "name": "pathapi",
- "type": "string",
- "label": "API URL suffix",
- "required": true,
- "helpMarkDown": "API URL suffix"
- },
- {
- "name": "TemplateSelector",
- "type": "pickList",
- "label": "Start from Policy Template",
- "required": false,
- "helpMarkDown": "Optionally choose a starting policy template to apply to the API",
- "defaultValue": "None",
- "options": {
- "None": "None",
- "CacheLookup": "Cache lookup",
- "CORS": "CORS",
- "Custom": "Custom",
- "Basic": "Basic",
- "JWT": "JWT",
- "IP": "IP",
- "RateByKey": "RateByKey",
- "QuotaByKey": "QuotaByKey",
- "HeaderCheck": "HeaderCheck"
- },
- "properties": {
- "EditableOptions": "True"
- }
- },
- {
- "name": "None",
- "type": "multiLine",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = NAN"
- },
- {
- "name": "Custom",
- "type": "multiline",
- "label": "None",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "helpMarkDown": "",
- "visibleRule": "TemplateSelector = Custom"
- },
- {
- "name": "CacheLookup",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\t\n\t\t\t\tAccept\n\t\t\t\tAccept-Charset\n\t\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Cache Lookup Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CacheLookup"
- },
- {
- "name": "Basic",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Basic Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = Basic"
- },
- {
- "name": "CORS",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\t*\n\t\t\t*\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default CORS Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = CORS"
- },
- {
- "name": "JWT",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tBase64 Encoded Key 1\n\t\t\t\n\t\t\tAudience 1\n\t\t\t\n\t\t\n\t\t\tIssuer 1\n\t\t\n\t\tvalue1value2\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default JWT validation Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = JWT"
- },
- {
- "name": "IP",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\taddress\n\t\t\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default IP Filtering Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = IP"
- },
- {
- "name": "RateByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Rate by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = RateByKey"
- },
- {
- "name": "QuotaByKey",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Quota by key Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = QuotaByKey"
- },
- {
- "name": "HeaderCheck",
- "type": "multiLine",
- "label": "Policy",
- "defaultValue": "\n\t\n\t\t\n\t\t\tvalue\n\t\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n\t\n\t\t\n\t\n",
- "required": false,
- "helpMarkDown": "Default Header Check Policy. Mind that this will replace any existing policy for that API. Add other policies manually if necessary!",
- "visibleRule": "TemplateSelector = HeaderCheck"
- },
- {
- "name": "MicrosoftApiManagementAPIVersion",
- "type": "pickList",
- "label": "Microsoft API Version",
- "required": true,
- "helpMarkDown": "Which version of the Management API should be used?",
- "defaultValue": "2017-03-01",
- "options": {
- "2017-03-01": "2017-03-01",
- "2018-01-01":"2018-01-01"
- },
- "properties": {
- "EditableOptions": "True"
- }
- }
- ],
- "dataSourceBindings": [
- {
- "target": "ResourceGroupName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "dataSourceName": "AzureResourceGroups"
- },
- {
- "name": "ApiPortals",
- "target": "ApiPortalName",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/$(endpoint.subscriptionId)/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service?api-version=2016-07-07",
- "resultSelector": "jsonpath:$.value[*].name",
- "parameters": {
- "ResourceGroupName": "$(ResourceGroupName)"
- }
- },
- {
- "target": "product1",
- "endpointId": "$(ConnectedServiceNameARM)",
- "endpointUrl": "{{endpoint.url}}/subscriptions/{{endpoint.subscriptionId}}/resourceGroups/$(ResourceGroupName)/providers/Microsoft.ApiManagement/service/$(ApiPortalName)/products?api-version=2017-03-01",
- "resultSelector": "jsonpath:$.value[*]",
- "resultTemplate": "{\"Value\" : \"{{{name}}}\", \"DisplayValue\" : \"{{{properties.displayName}}}\" }"
- }
- ],
- "execution": {
- "PowerShell3": {
- "target": "apimwsdl.ps1"
- }
- }
-}
\ No newline at end of file
diff --git a/apimwsdl/v3/task.json b/apimwsdl/v3/task.json
index 202147c..2156344 100644
--- a/apimwsdl/v3/task.json
+++ b/apimwsdl/v3/task.json
@@ -1,5 +1,5 @@
{
- "id": "9bfd810a-5e2b-4871-95d8-ae6e677d4224",
+ "id": "98bb53a5-c501-434b-9d48-fea3964850a7",
"name": "apimwsdl",
"friendlyName": "API Management - Create or Update API from WSDL",
"description": "API Management - Create or update API from WSDL",
diff --git a/apisecuritychecker/task.json b/apisecuritychecker/task.json
index d28609f..389c904 100644
--- a/apisecuritychecker/task.json
+++ b/apisecuritychecker/task.json
@@ -1,5 +1,5 @@
{
- "id": "2122de77-e114-41aa-973c-2daff243677a",
+ "id": "40a7b03c-0eaf-46c9-b813-1f4c903b0f08",
"name": "apisecuritychecker",
"friendlyName": "API Security Checker",
"description": "Makes sure all endpoints are secured",
diff --git a/intelequia.apim-3.6.0.vsix b/intelequia.apim-3.6.0.vsix
new file mode 100644
index 0000000..4e33ba6
Binary files /dev/null and b/intelequia.apim-3.6.0.vsix differ
diff --git a/intelequia.apim-3.6.1.vsix b/intelequia.apim-3.6.1.vsix
new file mode 100644
index 0000000..d0732a0
Binary files /dev/null and b/intelequia.apim-3.6.1.vsix differ
diff --git a/overview.md b/overview.md
index eb8cd04..c3f8ee0 100644
--- a/overview.md
+++ b/overview.md
@@ -7,6 +7,9 @@ The purpose of this extension is to bring Azure API Management into VSTS as part
is good to associate the release of your backends APIs with their corresponding facade APIs published against the API Gateway. On top of the API Management integration, the extension also
ships with an API Security Checker that helps validating that all endpoints of an API are well secured, this is of course only applicable to non-public APIs.
# Release Notes
+## v3.6.0
+* Added support for latest APIM versions
+* Fix apim create or update request with the new 2021-08-01 policy format
## v3.5.3
* Ability to inject policies through build artifacts - Sorin Pasa
## v3.5.2
diff --git a/stephane-eyskens.apim-3.5.3.vsix b/stephane-eyskens.apim-3.5.3.vsix
deleted file mode 100644
index f662cec..0000000
Binary files a/stephane-eyskens.apim-3.5.3.vsix and /dev/null differ
diff --git a/stephane-eyskens.apimprivate-3.4.8.vsix b/stephane-eyskens.apimprivate-3.4.8.vsix
deleted file mode 100644
index b84d19c..0000000
Binary files a/stephane-eyskens.apimprivate-3.4.8.vsix and /dev/null differ
diff --git a/vss-extension.json b/vss-extension.json
index 1534fab..708c8f6 100644
--- a/vss-extension.json
+++ b/vss-extension.json
@@ -2,8 +2,8 @@
"manifestVersion": 1,
"id": "apim",
"name": "API Management Suite",
- "version": "3.5.2",
- "publisher": "stephane-eyskens",
+ "version": "3.6.1",
+ "publisher": "intelequia",
"tags": [
"API",
"Security"
@@ -16,10 +16,10 @@
"public": true,
"links": {
"getstarted": {
- "uri": "https://github.com/stephaneey/azure-apim-extension"
+ "uri": "https://github.com/intelequia/azure-apim-extension"
},
"support": {
- "uri": "https://github.com/stephaneey/azure-apim-extension/issues"
+ "uri": "https://github.com/intelequia/azure-apim-extension/issues"
}
},
"targets": [