Private/Add-AdditionalEnvironment.ps1

function Invoke-AddEnvironments
{
    $adoRepo = $global:devops_gitRepo.Replace(' ', '')
    $adoOrg = $global:devops_projectFile.ADOOrgName
    $adoProject = $global:devops_projectFile.ADOProject
    
    $message = "Connecting to Power Platform"
    Write-Host $message

    Install-PowerAppsAdmin

    $message = "Connecting to Development Environment"
    Write-Host $message
    
    Write-Host ""

    [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12    
    if ($global:devops_ClientID) {
        $global:devops_DataverseCredType = "servicePrincipal"
    }
    else {
        Display-AzureLogins    
    }    
    if ($global:devops_DataverseCredType -eq "user") {
        Authenticate-PowerPlatform($global:devops_DataverseEmail)    
    }
    else {
        Write-Host "Using Service Principal"
        if ($global:devops_projectFile.ClientSecretAKVName) {
            $kvretrieve = az keyvault secret show --name $global:devops_projectFile.ClientSecretAKVName --vault-name $global:devops_projectFile.AzureKeyVaultName | ConvertFrom-Json
            $global:clientSecret = $kvretrieve.value            
        }
        else {            
            $clientKeySS = ($global:devops_configFile.Projects[$global:devops_projectConfigID].ClientSecret) | ConvertTo-SecureString
            $global:clientSecret = (New-Object PSCredential "user",$clientKeySS).GetNetworkCredential().Password
        }
            
            try {
                Add-PowerAppsAccount -ApplicationId $global:devops_ClientID -ClientSecret $global:clientSecret -TenantID $global:devops_TenantID    
                InvokeApi -Method PUT -Route "https://api.bap.microsoft.com/providers/Microsoft.BusinessAppPlatform/adminApplications/{$global:devops_ClientID}?api-version=2020-10-01"
            }
            catch {
                Write-Host $_
                pause
            }            
        }
    
    $connCICD = Get-AdminPowerAppEnvironment
    $options = $connCICD | ForEach-Object { "$($_.DisplayName) ($($_.Internal.properties.linkedEnvironmentMetadata.instanceUrl))" }
    
    do {
        $sel = Invoke-Menu -MenuTitle "---- Please Select your Additional Deplyoment Environment ------" -MenuOptions $options
        $CICDEnvironment = $connCICD[$sel]
     } until ($CICDEnvironment -ne "")
     Write-Host $CICDEnvironment.Internal.properties.linkedEnvironmentMetadata.instanceUrl
    
    if (!$Credentials) {
        Do {
            $Credentials = Get-Credential -Message "Enter the Credentials the Pipeline should use for Deploying to D365 / CDS"
        } Until (($Credentials.GetNetworkCredential().UserName -ne "") -and ($Credentials.GetNetworkCredential().Password -ne "")) 
    }
    if (!$username) {
        $username = $Credentials.GetNetworkCredential().UserName
        $password = $Credentials.GetNetworkCredential().Password
    }

    $PasswordSecret = Read-Host -Prompt "Set Password as Secret? [y/n]"
    if ($PasswordSecret.ToLower() -eq "y") {
        $secret = $true
    }
    else {
        $secret = $false
    }
    
    $message = "Creating variable groups in Azure DevOps"
    Write-Host $message
    
    try {
        $EnvironmentSafeName = $CICDEnvironment.Internal.properties.linkedEnvironmentMetadata.friendlyName.Replace(' ','')
        $varGroupCICD = az pipelines variable-group create --organization https://dev.azure.com/$adoOrg --project $adoProject --name "$adoRepo.D365$($EnvironmentSafeName)"  --variables d365username=$username --authorize $true | ConvertFrom-Json
        az pipelines variable-group variable create --organization https://dev.azure.com/$adoOrg --project $adoProject --name d365password --value """$password""" --secret $secret --group-id $varGroupCICD.id
        az pipelines variable-group variable create --organization https://dev.azure.com/$adoOrg --project $adoProject --name d365url --value $CICDEnvironment.Internal.properties.linkedEnvironmentMetadata.instanceUrl --group-id $varGroupCICD.id
    
        $buildYAML = Get-Content -Path "$global:devops_projectLocation\Build.yaml"
        $azureYAML = Get-Content -Path  (Join-Path $PSScriptRoot ..\Snippets\Environment.yaml)
        $azureYAML = $azureYAML.Replace('environmentName', $EnvironmentSafeName)
        $azureYAML = $azureYAML.Replace('replaceRepo', $adoRepo)
        if ($global:devops_projectFile.CICDEnvironmentName.Length -gt 0) {
            $azureYAML = $azureYAML.Replace('Deployment_Staging', $global:devops_projectFile.CICDEnvironmentName)
        }
        $buildYAML + $azureYAML | Set-Content -Path  "$global:devops_projectLocation\Build.yaml"
       
    }
    catch {
        Write-Host $_
        pause   
    }
    
    
    
}