Functions/AzDevOps/Add-CdsDevOpsVariableGroup.ps1

<#
    .SYNOPSIS
    Push CDS Instance data to a Az DevOps variable group.
#>

function Add-CdsDevOpsVariableGroup {
    [CmdletBinding()]
    param
    (        
        [Parameter(Mandatory = $false, ValueFromPipeline)]
        $CdsInstance
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);
    }    
    process {

        $orgName = $CdsInstance.ParentConnection.DevOpsSettings.OrganizationName;
        $projectName = $CdsInstance.ParentConnection.DevOpsSettings.ProjectName.Replace(" ", "%20");
        $token = $CdsInstance.ParentConnection.DevOpsSettings.Token;
        $apiVersion = "5.1-preview.1";
        $contentType = "application/json";

        $encodedPat = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$token"));
        $headers = @{Authorization = ("Basic {0}" -f $encodedPat) };

        $devOpsBaseApiUrl = "https://dev.azure.com/$orgName/$projectName/_apis";
        $apiUrl = "$devOpsBaseApiUrl/distributedtask/variablegroups?api-version=$apiVersion"

        $body = '{
            "variables": {
                "ConnectionString": {
                  "value": "[#ConnectionString#]"
                }
            },
            "type": "Vsts",
            "name": "[#Name#]",
            "description": ""
        }'
;
        $body = $body.Replace("[#ConnectionString#]", $CdsInstance.ConnectionString);
        $body = $body.Replace("[#Name#]", $CdsInstance.Name);

        $results = Invoke-RestMethod -Uri $apiUrl -Method Post -ContentType "$contentType; charset=UTF-8" -Body $body -Headers $headers -ErrorVariable "requestError";

    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Add-CdsDevOpsVariableGroup -Alias *;