Register-Environment Failing - azure-devops

I am having trouble creating a release definition on Azure DevOps. I believe the Register-Environment function in PowerShellOnTargetMachines.ps1 is failing:
try
{
$connection = Get-VssConnection -TaskContext $distributedTaskContext
Write-Verbose "Starting Register-Environment cmdlet call for environment : $environmentName with filter $machineFilter"
$environment = Register-Environment -EnvironmentName $environmentName -EnvironmentSpecification $environmentName -UserName $adminUserName -Password $adminPassword -WinRmProtocol $protocol -TestCertificate ($testCertificate -eq "true") -Connection $connection -TaskContext $distributedTaskContext -ResourceFilter $machineFilter
Write-Verbose "Completed Register-Environment cmdlet call for environment : $environmentName"
Write-Verbose "Starting Get-EnvironmentResources cmdlet call on environment name: $environmentName"
$resources = Get-EnvironmentResources -Environment $environment
if ($resources.Count -eq 0)
{
Write-Telemetry "Input_Validation" "No machine exists for given environment"
throw (Get-LocalizedString -Key "No machine exists under environment: '{0}' for deployment" -ArgumentList $environmentName)
}
$resourcesPropertyBag = Get-ResourcesProperties -resources $resources
}
With the following error (I have omitted some of my organization's information, but it is there and looks right):
2019-09-04T12:34:55.6886629Z ##[debug]VssConnection created
2019-09-04T12:34:55.7518340Z ##[debug]Starting Register-Environment cmdlet call for environment : [machine] with filter [machine]
2019-09-04T12:34:55.7843531Z ##[debug]Begin Create-Environment cmdlet
2019-09-04T12:34:55.7872731Z ##[debug]UserName=[username]
2019-09-04T12:34:55.7878292Z ##[debug]WinRmProtocol=HTTP
2019-09-04T12:34:55.7878658Z ##[debug]TestCertificate=False
2019-09-04T12:34:55.7878965Z ##[debug]Unable to create a environment object for given json - Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
2019-09-04T12:34:55.7879241Z ##[debug]projectName=[projectName]
2019-09-04T12:34:55.7879517Z ##[debug]Getting environment [machine] from DTL Service
2019-09-04T12:34:55.8485808Z ##[debug]Processed: ##vso[task.logissue type=error;code={"Task_Internal_Error":Page not found.};]
And I do not know what to do. Any ideas are appreciated. Thanks for taking the time to read my question.

Based on the details which from comment that Mike left, the issue should caused by the the task version you are using and its feature script we defined.
According to the ticket description you raised in DC ticket:
I am trying to use V2 of the following 'PowerShellOnTargetMachines'
PowerShell script for a release on azure devops, from
azure-pipeline-tasks.
the version of PowerShellOnTargetMachines you are using is 2.*.
We can get the Register-Environment cmdlet script with decompile tool follow the method I showed in this case.
You can see the parameters this cmdlet supported in 'PowerShellOnTargetMachines V2.*' does not include TaskContext and Connection. That's why you receive the error message "Unable to create a environment object for given json - Unexpected character encountered while parsing value". Because the parameter you input in the task does not match the configuration of Register-Environment cmdlet.
You can try with PowerShellOnTargetMachines V1.*. In 1.* we support the parameters TaskContext and Connection.

Related

How to stop Azure PostgreSQL replication using powershell with Azure Function

I am new to Azure Power shell and Azure functions.
I have requirement where I have to execute Powershell command to stop PostgreSQL replication
I created the Azure function app with default options and created the function. Inside the function I updated with Get-AzSubscription. I am getting error for all azure commands.
"Get-AzResource/Get-AzSubscription/Get-AzModule" is not recognized as a name of cmdlet or function or Scrip file or executable program
but I am able to execute the "Get-Date" and get required results
Please suggest how to fixes to this issue
Thanks in advance
Ramabadran
"Get-AzResource/Get-AzSubscription/Get-AzModule" is not recognized as a name of cmdlet or function or Scrip file or executable program
To run the PowerShell cmdlets on Azure PowerShell Runtime Stack Function App/Project, you need to uncomment the Az module in requirements.psd1 with the Az module version i.e., compatible with PowerShell Version you're using the Function App:
requirements.psd1:
#{
'Az' = '8.*'
}
run.ps1:
using namespace System.Net
param($Request, $TriggerMetadata)
Write-Host "PowerShell HTTP trigger function processed a request."
Connect-AzAccount -Tenant '<Azure-tenant-id>' -SubscriptionId '<Azure-Subscription-Id>'
$SubscriptionInfo = Get-AzSubscription -TenantId "<Azure-tenant-id>"
Write-Host $SubscriptionInfo
$body = "Hello Jahnavi, This HTTP triggered function executed successfully."
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = [HttpStatusCode]::OK
Body = $body
})
Result:
Note: Also, Install the Azure modules in the Function app workspace of the VS Code Terminal using these cmdlets Install-Module Az, Import-Module Az.

Powershell - A parameter cannot be found that matches parameter name

Something small I'm missing obviously, but I've followed several PS tutorials and I'm still getting the error.
I have a small PS script that I want to pass an argument to, this is to be eventually used in an Azure DevOps pipeline, but I can't even get this to work locally.
[CmdletBinding()]
param (
$EnvironmentName
)
$env = $EnvironmentName
Write-Host "$env"
Invoked with: ps HealthCheck.ps1 -EnvironmentName DEV
I keep getting the error
Get-Process : A parameter cannot be found that matches parameter name 'EnvironmentName'.
At line:1 char:20
+ ps HealthCheck.ps1 -EnvironmentName DEV

Template Validation Error - Error: Code=InvalidTemplate; Message=Deployment template validation failed:

I am having a bit of trouble deploying the template below:
azuredeploy.json file
One of the error message that has thrown:
'The template resource '[concat('nsg-create',copyIndex())]' at line '344' and column '9' is invalid. The api-version '2016-07-01' used to deploy the template does not support 'ResourceGroup' property. Please use api-version '2017-05-10' or later to deploy the template. Please see https://aka.ms/arm-template/#resources for usage details.'.
Code that have been used to deploy.
Context "Template Validation" {
It "Template $here\azuredeploy.json and parameter file passes validation" -TestCases $ParameterFileTestCases {
Param( $ParameterFile )
Update-Module -Name AzureRM -Force
$output = New-AzureRmResourceGroupDeployment -ResourceGroupName $TempValidationRG -Force -Mode Complete -TemplateFile "$here\azuredeploy.json" -TemplateParameterFile "$here\$ParameterFile" -ErrorAction Stop 5>&1
$output.ProvisioningState | Should -Be "Succeeded"
}
}
I have tried changing the API version, however, that still gave me the same error. I do not understand how to solve this issue.
I am trying to test the template through pester.
The output of Get-Module AzureRM* -ListAvailable :
AzureRM list
You need to use another api-version. Try 2017-05-10 this one.
Also, try updating the Azure Powershell to latest version.

TFS/VSTS Custom variables that aren't string cannot be used

I have been using TFS to create some release variables from PowerShell. I can then use '$Env:Server' in subsequent tasks in TFS to reference this output, this seems great to start with! EG:
Task 1 returns a server name then creates the TFS Variable:
Write-Host "##vso[task.setvariable variable=Server]"MySevrer
Task 2 Uses this information:
Write-Output $env:Server
MyServer
Upon outputting something in another format like an array or a hash table this does not work. The variable that gets created is just string as the documentation states using "Write-Host".
Task1 returns:
##vso[task.setvariable variable=Server] System.Collections.DictionaryEntry
Task 2 can not use this:
Write-Output $env:Server
System.Collections.DictionaryEntry
Output that is created
I have tried outputting this as a string in the array format, EG:
[String]$Server = '#{MyServer=#("192.168.0.1")}'
Write-Host "##vso[task.setvariable variable=Server]"$Server
When i refer to this I try to convert this back to an array within PowerShell, however, I have had issues with doing this inside a script as it will see the string as being a single array object. (Not an array with a value)
Does anyone know if it posable to parse hashtables or arrays between Team Service's tasks/Task Task groups based on information output by a Powershell task?
I have currently got around this by writing a wrapper/orchestration function but this is not the ideal way for us. We are currently on Version 15.117.26714.0 but i cannot see anything in newer versions.
ConvertTo-Json will do the trick, as mentioned by Daniel Mann.
Example:
In Azure Devops release pipeline, there is an Azure PowerShell task with following code:
$apps = Get-AzureRmResource -ResourceGroupName "$(ResourceGroupName)" -ResourceType Microsoft.Web/sites
$objectIdArray = New-Object System.Collections.ArrayList
foreach ($app in $apps) {
if (!$app.Identity) {
Write-Host "Enabling identity for $($app.Name) app service..."
$app = Set-AzureRmWebApp -Name $($app.Name) -ResourceGroupName "$(ResourceGroupName)" -AssignIdentity $true
} else {
Write-Host "$($app.Name) app service has $($app.Identity.PrincipalId) as the identity."
}
$objectIdArray.Add($($app.Identity.principalId))
}
$objectIdArrayJson = ($objectIdArray | ConvertTo-Json -Compress)
Write-Host "##vso[task.setvariable variable=objectIdArray;]$objectIdArrayJson"
Write-Host $env:objectIdArray
The following task is an Azure Resource Group Deployment task that has an overridden parameter:
-objectIdArray "$(objectIdArray)"
The release variable "$(objectIdArray)" has a value like:
["0512706a-0344-418a-9f25-5708d95e44aa","6047cbe6-c109-4aa7-8cfb-b473c088b1b1","68ee0d25-351f-44c8-aecf-cfc259f3cd97","44a6f3d6-23a3-443d-824b-445e0141f09c","805c3e6d-ab31-41f4-9d6c-8c9fc13ce
460","aa13b9db-200d-4c38-abf8-562a915ed8cd","8d1d7ec1-faa6-4af6-b732-331e51e86a90","02222b28-6370-4995-a633-29a1cdd08fd0","a48c21b1-b6ef-4582-b9a0-050965cb3614","9111421b-8535-4326-bbe9-1e891
33a0b56","5b1f6fca-599c-4895-ae4b-fabc0d3a4dd3","b12a935a-b1c3-4dec-b764-7c0a5307a766","8af7d615-c042-43b5-8ac0-736c6cf4ec3f","f0dd4dd9-e540-4e13-a8be-69ce08a6221c","b131e123-a87e-4faf-afed-4
37d6dbae4ab","af7f679b-1ac8-4991-b467-93ba4a16ec22","1bbb649c-b5e6-4f5c-a050-3a0cee0af985","4a7b728e-e8c6-49c0-bde2-54811708d5ab","3b190d28-c390-43c7-9269-1177afaf7b00","49f3777f-8668-4c72-82
60-753f65b933aa","727db5c4-ad56-457e-ad87-47b17c71e29b","801efff8-a852-4e7b-bc81-3d81d3bcfeb5","0947556e-7ece-4a36-a687-3c50f59e32f6"]
Pass them as JSON and use ConvertTo-Json and ConvertFrom-Json to convert them back and forth between JSON representations and PowerShell objects. When using ConvertTo-Json, be sure to use the -Compress flag.

Powershell Fails to Load Microsoft.ActiveDirectory.Management Through InstallShield, Works in ISE

I'm deep into a rabbit hole of why a simple powershell script (below) works via the ISE, but fails when run via InstallShield's Powershell custom action type.
I'm posting the InstallShield-ready version of the script. Trace-Info can be replaced with Write-Host and Set-Property can be commented out.
try
{
Import-Module ActiveDirectory
$all_gmsa_accts = Get-ADServiceAccount -Filter '*'
$valid_gmsa_accts = #( )
ForEach ($acct in $all_gmsa_accts) {
Trace-Info -LogMessage "Checking if account $($acct.Name) can be used on this machine"
if(Test-ADServiceAccount -Identity $acct.Name -WarningAction silentlyContinue) {
$valid_gmsa_accts += $acct.Name
}
}
$prop_value = $valid_gmsa_accts -join ','
$prop_name = "MANAGEDSERVICEACCOUNTS"
Set-Property -Name $prop_name -Value $prop_value
}
catch {
Trace-Info -LogMessage "Exception:"
Trace-Info -LogMessage $_.Exception.Message
}
When I run on either PS command line or PS ISE, I get expected results:
PS D:\ps> .\get-mgmd-test.ps1
Checking if account gmsauser1 can be used on this machine
Checking if account gmsauser2 can be used on this machine
Checking if account cantuseme can be used on this machine
Checking if account tsrcsvcuser1 can be used on this machine
Checking if account tsrcsvcuser2 can be used on this machine
Checking if account tsrcsvcuser3 can be used on this machine
Checking if account tsrcsvcuser4 can be used on this machine
Checking if account tsrcsvcuser5 can be used on this machine
When run from InstallShield, I get the below error messages in the log output.
Action start 11:34:42: GetManagedServiceAccounts.
MSI (c) (64:E8) [11:34:42:266]: Invoking remote custom action. DLL: C:\Users\ADMINI~1\AppData\Local\Temp\MSI9B2D.tmp, Entrypoint: m2
InstallShield: Attempting to load through CLR 4 APIs...
InstallShield: Getting meta host...
InstallShield: Enumerating available runtimes...
InstallShield: Highest available runtime: v4.0.30319
InstallShield: Trying to use highest runtime...
InstallShield: Using highest version runtime...
InstallShield: Loading assembly ClrPsHelper from resource 4097
InstallShield: Calling method with parameters [(System.UInt32)165, (System.String)C:\Users\administrator\AppData\Local\Temp\d397fb4e-db0a-445a-9dc8-7ee4520e6436\getmanagedsvcaccts.ps1]
PowerShell wrapper: Exception:
PowerShell wrapper: Could not load file or assembly 'Microsoft.ActiveDirectory.Management' or one of its dependencies. Invalid pointer (Exception from HRESULT: 0x80004003 (E_POINTER))
Action ended 11:34:44: GetManagedServiceAccounts. Return value 1.
So, does anyone have insight into the specific mechanics of the InstallShield powershell CA type shim(s)?
Why would it be trying to load Microsoft.ActiveDirectory.Management when the ISE does not?
Is there some way I can get the PS command line to function in the same profile as msiexec?