AzurePipelinesPS.psm1

$Script:PSModuleRoot = $PSScriptRoot
$Script:ModuleName = "AzurePipelinesPS"
$Script:ModuleDataRoot = (Join-Path -Path $env:APPDATA -ChildPath $Script:ModuleName)
$Script:ModuleDataPath = (Join-Path -Path $Script:ModuleDataRoot -ChildPath "ModuleData.json")
# Imported from [D:\_work\1\s\AzurePipelinesPS\Private]
# Get-APAgentPackage.ps1
Function Get-APAgentPackage
{
    <#
    .SYNOPSIS
 
    Returns available Azure Pipelines agent package versions.
 
    .DESCRIPTION
 
    Returns available Azure Pipelines agent package versions.
    The instance will provide a list of available compatible package versions and a url from which to download them.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Platform
 
    Operating system platform.
 
    .PARAMETER Version
     
    TFS version, this will provide the module with the api version mappings.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
     
    .INPUTS
 
    None. You cannot pipe objects to Get-APAgentPackage.
 
    .OUTPUTS
 
    PSCustomObject. Get-APAgentPackage returns all compatable agent package versions.
 
    .EXAMPLE
 
    C:\PS> Get-APAgentPackage -Platform 'ubuntu.14.04-x64' -Credential $pscredential
 
    .EXAMPLE
 
    C:\PS> Get-APAgentPackage -Platform 'Windows'
 
    .LINK
 
    https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=vsts
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter()]
        [string]
        $Instance,

        [Parameter(Mandatory)]
        [ValidateSet('Windows', 'ubuntu.16.04-x64', 'ubuntu.14.04-x64')]
        [string]
        $Platform,

        [Parameter()]
        [string]
        $ApiVersion,

        [Parameter()]
        [pscredential]
        $Credential
    )
    begin
    {
    }
    Process
    {
        Switch -Wildcard ($ApiVersion)
        {
            '*5.*'
            {
                Switch ($Platform)
                {
                    'Windows'
                    {
                        Return 'https://vstsagentpackage.azureedge.net/agent/2.140.2/vsts-agent-win-x64-2.140.2.zip'
                    }
                    'ubuntu.16.04-x64'
                    {
                        Return 'https://vstsagentpackage.azureedge.net/agent/2.140.2/vsts-agent-linux-x64-2.140.2.tar.gz'
                    }
                    'ubuntu.14.04-x64'
                    {
                        Return 'https://vstsagentpackage.azureedge.net/agent/2.140.2/vsts-agent-linux-x64-2.140.2.tar.gz'
                    }
                }
            }
            Default
            {
                $apiEndpoint = Get-APApiEndpoint -ApiType 'packages-agent'
                [uri] $uri = Set-APUri -Instance $Instance -ApiEndpoint $apiEndpoint
                $invokeAPRestMethodSplat = @{
                    Method     = 'GET'
                    Uri        = $uri
                    Credential = $Credential
                }
                $results = Invoke-APRestMethod @invokeAPRestMethodSplat
                Switch ($Platform)
                {
                    'Windows'
                    {
                        Return $Results.Value | Where-Object {$Psitem.Platform -eq 'win7-x64'} | Select-Object -ExpandProperty 'downloadUrl'
                    }
                    'ubuntu.16.04-x64'
                    {
                        Return $Results.Value | Where-Object {$Psitem.Platform -eq 'ubuntu.16.04-x64'} | Select-Object -ExpandProperty 'downloadUrl'
                    }
                    'ubuntu.14.04-x64'
                    {
                        Return $Results.Value | Where-Object {$Psitem.Platform -eq 'ubuntu.14.04-x64'} | Select-Object -ExpandProperty 'downloadUrl'
                    }
                }
            }
        }
    }
}

# Get-APApiEndpoint.ps1
function Get-APApiEndpoint
{    
    <#
    .SYNOPSIS
 
    Returns the api uri endpoint.
 
    .DESCRIPTION
 
    Returns the api uri endpoint base on the api type.
 
    .PARAMETER ApiType
 
    Type of the api endpoint to use.
 
    .OUTPUTS
 
    String, The uri endpoint that will be used by Set-APUri.
 
    .EXAMPLE
 
    C:\PS> Get-APApiEndpoint -ApiType release-releases
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-5.0
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]
        $ApiType
    )

    begin
    {
    }

    process
    {
        Switch ($ApiType)
        {
            'build-builds'
            {
                Return '_apis/build/builds'
            }
            'build-buildId'
            {
                Return '_apis/build/builds/{0}'
            }
            'build-definitions'
            {
                Return '_apis/build/definitions'
            }
            'build-definitionId'
            {
                Return '_apis/build/definitions/{0}'
            }
            'packages-agent'
            {
                Return '_apis/distributedTask/packages/agent'
            }
            'release-releases'
            {
                Return '_apis/release/releases'
            }
            'release-definitions'
            {
                Return '_apis/release/definitions'
            }
            'release-definitionId'
            {
                Return '_apis/release/definitions/{0}'
            }
            'release-releaseId'
            {
                Return '_apis/release/releases/{0}'
            }
            'release-manualInterventionId'
            {
                Return '_apis/release/releases/{0}/manualinterventions/{1}'
            }
            'release-environmentId'
            {
                Return '_apis/release/releases/{0}/environments/{1}'
            }
            'release-taskId'
            {
                Return '_apis/release/releases/{0}/environments/{1}/deployPhases/{2}/tasks/{3}'
            }
            'distributedtask-queues'
            {
                Return '_apis/distributedtask/queues'
            }
            'distributedtask-deploymentgroups'
            {
                Return '_apis/distributedtask/deploymentgroups'
            }
            'distributedtask-deploymentGroupId'
            {
                Return '_apis/distributedtask/deploymentgroups/{0}'
            }
            'distributedtask-targets'
            {
                Return '_apis/distributedtask/deploymentgroups/{0}/targets'
            }
            'distributedtask-targetId'
            {
                Return '_apis/distributedtask/deploymentgroups/{0}/targets/{1}'
            }
            'distributedtask-variablegroups'
            {
                Return '_apis/distributedtask/variablegroups'
            }
            'distributedtask-variablegroupId'
            {
                Return '_apis/distributedtask/variablegroups/{0}'
            }
            'git-repositories'
            {
                Return '_apis/git/repositories'
            }
            'git-repositoryId'
            {
                Return '_apis/git/repositories/{0}'
            }
            'project-projects'
            {
                Return '_apis/projects'
            }
            'taskgroup-taskgroups'
            {
                Return '_apis/distributedtask/taskgroups'
            }
            default
            {
                Write-Error "[$($MyInvocation.MyCommand.Name)]: [$ApiType] is not supported" -ErrorAction Stop
            }
        }
    }

    end
    {
    }
}

# Get-APApiVersion.ps1
function Get-APApiVersion
{    
    <#
    .SYNOPSIS
 
    Returns the api version available for the TFS version provided.
 
    .DESCRIPTION
 
    Returns the api version available for the TFS version provided.
 
    .PARAMETER Version
     
    TFS version, this will provide the module with the api version mappings.
 
    .OUTPUTS
 
    String, The api version available for the TFS version provided.
 
    .EXAMPLE
 
    C:\PS> Get-APApiEndpoint -ApiType release-releases
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-5.0
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter()]
        [string]
        $Version
    )

    begin
    {
    }

    process
    {
        Switch ($Version)
        {
            'vNext'
            {
                Return '5.0-preview'
            }
            '2018 Update 2'
            {
                Return '4.0-preview'
            }
            '2018 RTW'
            {
                Return '4.0'
            }
            '2017 Update 2'
            {
                Return '3.2'
            }
            '2017 Update 1'
            {
                Return '3.1'
            }
            '2017 RTW'
            {
                Return '3.0'
            } 
            '2015 Update 4'
            {
                Return '2.3'
            } 
            '2015 Update 3'
            {
                Return '2.3'
            } 
            '2015 Update 2'
            {
                Return '2.2'
            } 
            '2015 Update 1'
            {
                Return '2.1'
            } 
            '2015 RTW'
            {
                Return '2.0'
            }
            default
            {
                Write-Error "[$($MyInvocation.MyCommand.Name)]: [$Version] is not supported, run 'Save-APSession -Version' to populate module data. " -ErrorAction Stop
            }
        }
    }

    end
    {
    }
}

# Set-APAuthenticationType.ps1
function Set-APAuthenticationType
{    
    <#
    .SYNOPSIS
 
    Sets the authentication type used by Invoke-APRestMethod.
 
    .DESCRIPTION
 
    Sets the authentication type used by Invoke-APRestMethod.
    Default authentication will use the pesonal access token that is stored in session data, unless a credential is provided.
 
    .PARAMETER InputObject
     
    The splat parameters used by Invoke-APRestMethod.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
     
    .OUTPUTS
 
    PSObject, The modifed inputobject.
 
    .EXAMPLE
 
    C:\PS> Set-APAuthenticationType -InputObject $inputObject
 
    .EXAMPLE
 
    C:\PS> Set-APAuthenticationType -InputObject $inputObject -Credential $pscredential
 
    .LINK
 
    https://docs.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/authentication-guidance?view=vsts
    #>

    [CmdletBinding()]
    param 
    (
        [Parameter(Mandatory)]
        [PSObject]
        $InputObject,

        [Parameter()]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }

    process
    {
        If ($Credential)
        {
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Authenticating with the provided credential."
            $InputObject.Credential = $Credential
        }
        ElseIf ($PersonalAccessToken)
        {
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Authenticating with the stored personal access token."
            $PersonalAccessTokenToken = Unprotect-APSecurePersonalAccessToken -PersonalAccessToken $PersonalAccessToken
            $encodedPersonalAccessToken = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$PersonalAccessTokenToken"))
            $InputObject.Headers = @{Authorization = "Basic $encodedPersonalAccessToken"}
        }
        Else
        {
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Authenticating with default credentials"
            $InputObject.UseDefaultCredentials = $true
        }
    }

    end
    {
        Return $InputObject
    }
}

# Set-APQueryParameters.ps1
function Set-APQueryParameters
{    
    <#
    .SYNOPSIS
 
    Returns the formated query parameter string.
 
    .DESCRIPTION
 
    Returns the formated query parameter string.
 
    .PARAMETER InputObject
     
    The PS bound parameters.
 
    .OUTPUTS
 
    String, The formated query parameter string.
 
    .EXAMPLE
 
    C:\PS> Set-APQueryParameters -InputObject $PSBoundParameters
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-5.0
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter()]
        [object]
        $InputObject
    )

    begin
    {
    }

    process
    {
        $nonQueryParams = @(
            'Instance'
            'Collection'
            'Project'
            'ApiVersion'
            'PersonalAccessToken'
            'Session'
            'Credential'
            'Verbose'
            'Debug'
            'ErrorAction'
            'WarningAction' 
            'InformationAction' 
            'ErrorVariable' 
            'WarningVariable' 
            'InformationVariable' 
            'OutVariable' 
            'OutBuffer'
        )
        $queryParams = Foreach ($key in $InputObject.Keys)
        {
            If ($nonQueryParams -contains $key)
            {
                Continue
            }
            ElseIf ($key -eq 'Top')
            {
                "`$$key=$($InputObject.$key)"
            }
            ElseIf ($InputObject.$key.count)
            {
                "$key={0}" -f ($InputObject.$key -join ',')
            }
            else
            {
                "$key=$($InputObject.$key)"                    
            }
        }
        Return ($queryParams -join '&').ToLower()
    }

    end
    {
    }
}

# Set-APUri.ps1
function Set-APUri
{    
    <#
    .SYNOPSIS
 
    Sets the uri used by Invoke-APRestMethod.
 
    .DESCRIPTION
 
    Sets the uri used by Invoke-APRestMethod.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    The value for collection should be DefaultCollection for both Team Services and TFS.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER Query
 
    Url query parameter.
 
    .PARAMETER ApiEndpoint
 
    The api endpoint provided by Get-APApiEndpoint.
 
    .PARAMETER ApiVersion
 
    Version of the api to use.
 
    .OUTPUTS
 
    Uri, The uri that will be used by Invoke-APRestMethod.
 
    .EXAMPLE
 
    C:\PS> Set-APUri -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -ApiEndpoint _apis/Release/releases/4 -ApiVersion '5.0-preview.6'
 
    .EXAMPLE
 
    C:\PS> Set-APUri -ApiEndpoint _apis/Release/releases/4 -ApiVersion '5.0-preview.6' -Query 'project=myFirstProject&isdeleted=true&expand=environments'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/?view=vsts-rest-5.0
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance,

        [Parameter()]
        [string]
        $Collection,

        [Parameter()]
        [string]
        $Project,

        [Parameter()]
        [string]
        $Query,

        [Parameter(Mandatory)]
        [string]
        $ApiEndpoint,

        [Parameter()]
        [string]
        $ApiVersion
    )

    begin
    {
    }

    process
    {   
        If ($Instance.AbsoluteUri -and $Collection -and $Project -and ($ApiEndpoint -match 'release') -and ($ApiVersion -match '5.*') -and $Query)
        {
            # Append .vsrm prefix to instance if the api version is VNext and the api endpoint matches release with query
            [uri] $output = '{0}{1}/{2}/{3}?{4}&api-version={5}' -f $Instance.AbsoluteUri.replace($Instance.Host, "vsrm.$($Instance.Host)"), $Collection, $Project, $ApiEndpoint, $Query, $ApiVersion       
        }
        ElseIf ($Instance.AbsoluteUri -and $Collection -and $Project -and $ApiEndpoint -and $ApiVersion -and $Query)
        {
            [uri] $output = '{0}{1}/{2}/{3}?{4}&api-version={5}' -f $Instance.AbsoluteUri, $Collection, $Project, $ApiEndpoint, $Query, $ApiVersion       
        } 
        ElseIf ($Instance.AbsoluteUri -and $Collection -and $Project -and ($ApiEndpoint -match 'release') -and ($ApiVersion -match '5.*'))
        {
            # Append .vsrm prefix to instance if the api version is VNext and the api endpoint matches release without query
            [uri] $output = '{0}{1}/{2}/{3}?api-version={4}' -f $Instance.AbsoluteUri.replace($Instance.Host, "vsrm.$($Instance.Host)"), $Collection, $Project, $ApiEndpoint, $ApiVersion       
        }          
        ElseIf ($Instance.AbsoluteUri -and $Collection -and $Project -and $ApiEndpoint -and $ApiVersion)
        {
            [uri] $output = '{0}{1}/{2}/{3}?api-version={4}' -f $Instance.AbsoluteUri, $Collection, $Project, $ApiEndpoint, $ApiVersion       
        }  
        ElseIf ($Instance.AbsoluteUri -and $Collection -and $ApiEndpoint -and $ApiVersion)
        {
            [uri] $output = '{0}{1}/{2}?api-version={3}' -f $Instance.AbsoluteUri, $Collection, $ApiEndpoint, $ApiVersion 
        }      
        ElseIf ($Instance.AbsoluteUri -and $ApiEndpoint)
        {
            [uri] $output = '{0}{1}' -f $Instance.AbsoluteUri, $ApiEndpoint
        }
    }

    end
    {
        Return $output
    }
}


# Unprotect-APSecurePersonalAccessToken.ps1
Function Unprotect-APSecurePersonalAccessToken
{
    <#
    .SYNOPSIS
 
    Returns decrypted personal access token.
 
    .DESCRIPTION
 
    Returns decrypted personal access token that is stored in the session data.
 
    .PARAMETER PersonalAccessToken
 
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
         
    .OUTPUTS
 
    String, unsecure personal access token.
 
    .EXAMPLE
 
    C:\PS> Unprotect-SecurePersonalAccessToken
 
    .EXAMPLE
 
    C:\PS> Unprotect-SecurePersonalAccessToken -Path $path
 
    .LINK
 
    https://docs.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/authentication-guidance?view=vsts
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory)]
        [Security.SecureString]
        $PersonalAccessToken
    )
    Process
    {
        $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PersonalAccessToken)
        $plainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
        Return $plainText
    }
}

# Imported from [D:\_work\1\s\AzurePipelinesPS\Public]
# Add-APDeploymentGroup.ps1
function Add-APDeploymentGroup
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipeline deployment group.
 
    .DESCRIPTION
 
    Creates an Azure Pipeline deployment group.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Name
     
    Name of the deployment group.
 
    .PARAMETER Description
     
    Description of the deployment group.
     
    .PARAMETER PoolId
     
    Identifier of the deployment pool in which deployment agents are registered.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines deployment group.
 
    .EXAMPLE
 
    C:\PS> Add-APDeploymentGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/deploymentgroups/add?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [string]
        $PoolId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = @{
            Name        = $Name
            Description = $Description
            PoolId      = $PoolId
        }
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-deploymentGroupId') -f $DeploymentGroupID
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method      = 'POST'
            Uri         = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body        = $body
            ContentType = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Add-APVariableGroup.ps1
function Add-APVariableGroup
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipeline variable group.
 
    .DESCRIPTION
 
    Creates an Azure Pipeline variable group.
 
  .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Description
     
    Sets description of the variable group.
  
    .PARAMETER Name
     
    Sets name of the variable group.
 
    .PARAMETER Variables
     
    Sets variables contained in the variable group.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines variable group.
 
    .EXAMPLE
 
    $varibales = @{
        Var1 = 'updated val1'
        Var2 = 'updated val2'
    }
    $addAPVariableGroupSplat = @{
        Description = 'my variable group'
        Name = 'myVariableGroup'
        Variables = $varibales
        Instance = 'https://myproject.visualstudio.com'
        Collection = 'DefaultCollection'
        Project = 'myFirstProject'
    }
    Add-APVariableGroup @addAPVariableGroupSplat
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/variablegroups/add?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [object]
        $Variables
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        If($Variables.GetType().Name -eq 'hashtable')
        {
            $_variables = @{}
            Foreach ($token in $Variables.Keys)
            {
                $_variables.$token = @{
                    Value = $Variables.$token
                }
            }
        }
        else 
        {
            $_variables = $Variables    
        }
        $body = @{
            Name        = $Name
            Description = $Description
            Type        = 'Vsts'
            Variables   = $_variables
        }
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-VariableGroupId') -f $VariableGroupID
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'POST'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body                = $body
            ContentType         = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Format-APTemplate.ps1
Function Format-APTemplate
{
    <#
    .SYNOPSIS
 
    Replaces tokens in a json template.
 
    .DESCRIPTION
 
    Replaces tokens in a json template. The json template tokens should be unique strings like '%Project%' or '__Collection__'.
    By passing key value pairs with the InputObject parameter @{'%Project% = 'myProject'} the tokens will be replaced with the values.
    Templates can be created by using Get-APBuildDefinition or Get-APReleaseDefinition and tokenizing it.
 
    .PARAMETER Path
     
    Path to the build/release json template that contains tokens.
     
    .PARAMETER InputObject
     
    Object, that contains key value pairs for token replacement.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSobject, Azure Pipelines build/release template. Pass the template to Publish-APBuild or Publish-APRelease.
 
    .EXAMPLE
 
    C:\PS> $inputObject = @{
        %Project% = 'myProject'
    }
    C:\PS> Format-APTemplate -Path '.\myTemplate.json' -InputObject $inputObject
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/list?view=vsts-rest-5.0
    #>

    Param
    (
        [Parameter(Mandatory)]
        [string]
        $Path,

        [Parameter(Mandatory)]
        [object]
        $InputObject
    )

    Begin
    {
    }
    Process
    {        
        $templateJson = Get-Content -Path $Path -Raw  
        $InputObject.Keys | ForEach-Object -Process { $templateJson = $templateJson -replace $_, $InputObject.Item($_) }
        ConvertFrom-Json -Inputobject $templateJson 
    }
}
# Get-APBuild.ps1
function Get-APBuild
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline build.
 
    .DESCRIPTION
 
    Returns Azure Pipeline build based by build id.
    The id can be retrieved by using Get-APBuildList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER BuildId
 
    The ID of the build
 
    .PARAMETER PropertyFilters
     
    Undocumented
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APBuild -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -BuildId 7
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/builds/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [int]
        $BuildId,

        [Parameter()]
        [string]
        $PropertyFilters
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'build-buildId') -f $BuildId
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APBuildDefinition.ps1
function Get-APBuildDefinition
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline build definitions.
 
    .DESCRIPTION
 
    Returns Azure Pipeline build definitions by definition id.
    The id can be retrieved by using Get-APBuildDefinitionList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DefinitionID
 
    The ID of the definition.
 
    .PARAMETER Revision
 
    The revision number to retrieve. If this is not specified, the latest version will be returned.
 
    .PARAMETER MinMetricsTime
 
    If specified, indicates the date from which metrics should be included.
 
    .PARAMETER PropertyFilters
 
    A comma-delimited list of properties to include in the results.
 
    .PARAMETER IncludeLatestBuilds
 
    Indicates whether to include or exclude the latest builds.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APBuild -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/definitions/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [int]
        $DefinitionID,

        [Parameter()]
        [int]
        $Revision,

        [Parameter()]
        [datetime]
        $MinMetricsTime,
       
        [Parameter()]
        [string[]]
        $PropertyFilters,

        [Parameter()]
        [switch]
        $IncludeLatestBuilds
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {

        $apiEndpoint = (Get-APApiEndpoint -ApiType 'build-definitionId') -f $DefinitionID
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APBuildDefinitionList.ps1
function Get-APBuildDefinitionList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline build definitions.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline build definitions based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER TaskIdFilter
 
    If specified, filters to definitions that use the specified task.
 
    .PARAMETER IncludeLatestBuilds
 
    Indicates whether to return the latest and latest completed builds for this definition.
 
    .PARAMETER IncludeAllProperties
 
    Indicates whether to return the latest and latest completed builds for this definition.
 
    .PARAMETER NotBuiltAfter
 
    If specified, filters to definitions that do not have builds after this date.
 
    .PARAMETER BuiltAfter
 
    If specified, filters to definitions that have builds after this date.
 
    .PARAMETER Path
 
    If specified, filters to definitions under this folder.
 
    .PARAMETER DefinitionIds
 
    A comma-delimited list that specifies the IDs of definitions to retrieve.
 
    .PARAMETER MinMetricsTime
 
    If specified, indicates the date from which metrics should be included.
 
    .PARAMETER ContinuationToken
 
    A continuation token, returned by a previous call to this method, that can be used to return the next set of definitions.
 
    .PARAMETER Top
 
    The maximum number of definitions to return.
 
    .PARAMETER QueryOrder
 
    Indicates the order in which definitions should be returned.
 
    .PARAMETER RepositoryType
 
    If specified, filters to definitions that have a repository of this type.
 
    .PARAMETER RepositoryId
 
    A repository ID. If specified, filters to definitions that use this repository.
 
    .PARAMETER Name
 
    If specified, filters to definitions whose names match this pattern.
 
    .PARAMETER YamlFilename
 
    If specified, filters to YAML definitions that match the given filename.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APBuildDefinitionList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/definitions/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $TaskIdFilter,

        [Parameter()]
        [bool]
        $IncludeLatestBuilds,

        [Parameter()]
        [bool]
        $IncludeAllProperties,

        [Parameter()]
        [datetime]
        $NotBuiltAfter,

        [Parameter()]
        [datetime]
        $BuiltAfter,

        [Parameter()]
        [string]
        $Path,

        [Parameter()]
        [int[]]
        $DefinitionIds,

        [Parameter()]
        [datetime]
        $MinMetricsTime,

        [Parameter()]
        [string]
        $ContinuationToken,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [string]
        [ValidateSet('ascending', 'descending')]
        $QueryOrder,

        [Parameter()]
        [string]
        $RepositoryType,

        [Parameter()]
        [string]
        $RepositoryId,

        [Parameter()]
        [string]
        $Name,

        [Parameter()]
        [string]
        $YamlFilename
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'build-definitions'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Get-APBuildList.ps1
function Get-APBuildList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline builds.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline builds based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
    .PARAMETER RepositoryId
 
    If specified, filters to builds that built from this repository.
 
    .PARAMETER BuildIds
 
    A comma-delimited list that specifies the IDs of builds to retrieve.
 
    .PARAMETER BranchName
 
    If specified, filters to builds that built branches that built this branch.
 
    .PARAMETER QueryOrder
 
    The order in which builds should be returned.
 
    .PARAMETER DeletedFilter
 
    Indicates whether to exclude, include, or only return deleted builds.
 
    .PARAMETER MaxBuildsPerDefinition
 
    The maximum number of builds to return per definition.
 
    .PARAMETER ContinuationToken
 
    A continuation token, returned by a previous call to this method, that can be used to return the next set of builds.
 
    .PARAMETER Top
 
    The maximum number of builds to return.
 
    .PARAMETER Properties
 
    A comma-delimited list of properties to retrieve.
 
    .PARAMETER TagFilters
 
    A comma-delimited list of tags. If specified, filters to builds that have the specified tags.
 
    .PARAMETER ResultFilter
     
    If specified, filters to builds that match this result.
 
    .PARAMETER StatusFilter
 
    If specified, filters to builds that match this status.
 
    .PARAMETER ReasonFilter
 
    If specified, filters to builds that match this reason.
 
    .PARAMETER RequestedFor
     
    If specified, filters to builds requested for the specified user.
 
    .PARAMETER MaxTime
         
    If specified, filters to builds requested for the specified user.
 
    .PARAMETER MinTime
 
    If specified, filters to builds that finished/started/queued after this date based on the queryOrder specified.
 
    .PARAMETER BuildNumber
 
    If specified, filters to builds that match this build number. Append * to do a prefix search.
 
    .PARAMETER Queues
 
    A comma-delimited list of queue IDs. If specified, filters to builds that ran against these queues.
 
    .PARAMETER Definitions
 
    A comma-delimited list of definition IDs. If specified, filters to builds for these definitions.
 
    .PARAMETER RepositoryType
     
    If specified, filters to builds that built from repositories of this type.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APBuildList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/builds/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $RepositoryId,

        [Parameter()]
        [int[]]
        $BuildIds,

        [Parameter()]
        [string]
        $BranchName,

        [Parameter()]
        [string]
        [ValidateSet('finishTimeAscending', 'finishTimeDescending', 'queueTimeAscending', 'queueTimeDescending', 'startTimeAscending', 'startTimeDescending')]
        $QueryOrder,

        [Parameter()]
        [ValidateSet('excludeDeleted', 'includeDeleted', 'onlyDeleted')]
        [string]
        $DeletedFilter,   
        
        [Parameter()]
        [int]
        $MaxBuildsPerDefinition,

        [Parameter()]
        [string]
        $ContinuationToken,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [string[]]
        $Properties,

        [Parameter()]
        [string[]]
        $TagFilters,

        [Parameter()]
        [ValidateSet('canceled', 'failed', 'none', 'partiallySucceeded', 'succeeded')]
        [string]
        $ResultFilter,

        [Parameter()]
        [ValidateSet('all', 'cancelling', 'completed', 'inProgress', 'none', 'notStarted', 'postponed')]
        [string]
        $StatusFilter,

        [Parameter()]
        [ValidateSet('all', 'batchedCI', 'buildCompletion', 'checkInShelveset', 'individualCI', 'manual', 'none', 'pullRequest', 'schedule', 'triggered', 'userCreated', 'validateShelveset')]
        [string]
        $ReasonFilter,

        [Parameter()]
        [string]
        $RequestedFor,

        [Parameter()]
        [datetime]
        $MaxTime,

        [Parameter()]
        [datetime]
        $MinTime,

        [Parameter()]
        [string]
        $BuildNumber,

        [Parameter()]
        [int[]]
        $Queues,

        [Parameter()]
        [int[]]
        $Definitions,

        [Parameter()]
        [string]
        $RepositoryType
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'build-builds'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'GET'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APDeploymentGroup.ps1
function Get-APDeploymentGroup
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline deployment group.
 
    .DESCRIPTION
 
    Returns Azure Pipeline deployment group by deployment group id.
    The deployment group id can be retrieved by using Get-APDeploymentGroupList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
 
    ID of the deployment group.
 
    .PARAMETER ActionFilter
 
    Get the deployment group only if this action can be performed on it.
 
    .PARAMETER Expand
 
    Include these additional details in the returned objects.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines deployment group.
 
    .EXAMPLE
 
    C:\PS> Get-APDeploymentGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/deploymentgroups/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupID,

        [Parameter()]
        [ValidateSet('manage', 'none', 'use')]
        [string]
        $ActionFilter,

        [Parameter()]
        [ValidateSet('machines', 'none', 'tags')]
        [string]
        $Expand
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-deploymentGroupId') -f $DeploymentGroupID
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'GET'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken        
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APDeploymentGroupList.ps1
function Get-APDeploymentGroupList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline deployment groups.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline deployment groups based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Name
 
    Name of the deployment group.
 
    .PARAMETER ActionFilter
 
    Get the deployment group only if this action can be performed on it.
 
    .PARAMETER Expand
 
    Include these additional details in the returned objects.
 
    .PARAMETER ContinuationToken
 
    Get deployment groups with names greater than this continuationToken lexicographically.
 
    .PARAMETER Top
 
    Maximum number of deployment groups to return. Default is 1000.
 
    .PARAMETER Ids
 
    Comma separated list of IDs of the deployment groups.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines deployment group.
 
    .EXAMPLE
 
    C:\PS> Get-APDeploymentGroupList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -Name Dev
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/deploymentgroups/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $Name,

        [Parameter()]
        [ValidateSet('manage', 'none', 'use')]
        [string]
        $ActionFilter,

        [Parameter()]
        [ValidateSet('machines', 'none', 'tags')]
        [string]
        $Expand,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [int[]]
        $Ids
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'distributedtask-deploymentgroups'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'GET'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APProjectList.ps1
function Get-APProjectList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline build projects.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline build projects based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER ContinuationToken
 
    A continuation token, returned by a previous call to this method, that can be used to return the next set of definitions.
 
    .PARAMETER Top
 
    The maximum number of definitions to return.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APProjectList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/definitions/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $ContinuationToken,

        [Parameter()]
        [int]
        $Top
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'project-projects'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Get-APQueue.ps1
Function Get-APQueue
{
    <#
    .SYNOPSIS
 
    Returns an Azure Pipeline queue.
 
    .DESCRIPTION
 
    Returns an Azure Pipeline queue based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER QueueName
 
    Filters queues whose names start with this prefix.
 
    .PARAMETER ActionFilter
 
    Filter Queues based on the permission mentioned.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines queue(s)
 
    .EXAMPLE
 
    C:\PS> Get-APQueue -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/builds/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $QueueName,

        [Parameter()]
        [ValidateSet('none','manage','use')]
        [string]
        $ActionFilter
    )
    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'distributedtask-queues'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APRelease.ps1
function Get-APRelease
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline release.
 
    .DESCRIPTION
 
    Returns Azure Pipeline release by release id.
    The id can be retrieved by using Get-APReleaseList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER ReleaseId
     
    Id of the release.
 
    .PARAMETER ApprovalFilters
     
    A filter which would allow fetching approval steps selectively based on whether it is automated, or manual. This would also decide whether we should fetch pre and post approval snapshots. Assumes All by default.
 
    .PARAMETER PropertyFilters
     
    A comma-delimited list of extended properties to be retrieved. If set, the returned Release will contain values for the specified property Ids (if they exist). If not set, properties will not be included.
 
    .PARAMETER Expand
     
    A property that should be expanded in the release.
 
    .PARAMETER TopGateRecords
     
    Number of release gate records to get. Default is 5.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines release(s)
 
    .EXAMPLE
 
    C:\PS> Get-APRelease -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [string]
        $ReleaseId,

        [Parameter()]
        [string]
        $ApprovalFilters,

        [Parameter()]
        [string]
        $PropertyFilters,

        [Parameter()]
        [string]
        [ValidateSet('none', 'tasks')]
        $Expand,

        [Parameter()]
        [int]
        $TopGateRecords
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
  
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'release-releaseId') -f $ReleaseId
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APReleaseDefinition.ps1
function Get-APReleaseDefinition
{
    <#
    .SYNOPSIS
 
    Returns an Azure Pipeline release definition.
 
    .DESCRIPTION
 
    Returns an Azure Pipeline release definition by definition id.
    The id can be retrieved by using Get-APReleaseDefinitionList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
     
    .PARAMETER DefinitionId
     
    Releases with names starting with searchText.
 
    .PARAMETER PropertyFilters
     
    The property that should be expanded in the list of releases.
 
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines release definition(s).
 
    .EXAMPLE
 
    C:\PS> Get-APReleaseDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DefinitionId 5
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [int]
        $DefinitionId,

        [Parameter()]
        [string[]]
        $PropertyFilters
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'release-definitionId') -f $DefinitionId
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Get-APReleaseDefinitionList.ps1
function Get-APReleaseDefinitionList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline release definitions.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline release definitions based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
     
    .PARAMETER SearchText
     
    Releases with names starting with searchText.
 
    .PARAMETER Expand
     
    The property that should be expanded in the list of releases.
 
    .PARAMETER ArtifactType
     
    Release definitions with given artifactType will be returned. Values can be Build, Jenkins, GitHub, Nuget, Team Build (external), ExternalTFSBuild, Git, TFVC, ExternalTfsXamlBuild.
 
    .PARAMETER Top
     
    Number of releases to get. Default is 50.
 
    .PARAMETER ContinuationToken
     
    Gets the releases after the continuation token provided.
 
    .PARAMETER QueryOrder
     
    Gets the results in the defined order of created date for releases. Default is descending.
 
    .PARAMETER Path
     
    Gets the release definitions under the specified path.
     
    .PARAMETER IsExactNameMatch
     
    Set to 'true' to get the release definitions with exact match as specified in searchText. Default is 'false'.
 
    .PARAMETER TagFilter
     
    A comma-delimited list of tags. Only releases with these tags will be returned.
 
    .PARAMETER PropertyFilters
     
    A comma-delimited list of extended properties to retrieve.
 
    .PARAMETER DefinitionIdFilter
     
    A comma-delimited list of release definitions to retrieve.
 
    .PARAMETER IsDeleted
     
    Gets the soft deleted releases, if true.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines release definition(s)
 
    .EXAMPLE
 
    C:\PS> Get-APReleaseDefinitionList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $SearchText,

        [Parameter()]
        [string]
        [ValidateSet('approvals', 'artifacts', 'environments', 'manualInterventions', 'none', 'tags', 'variables')]
        $Expand,

        [Parameter()]
        [string]
        $ArtifactType,

        [Parameter()]
        [string]
        $Top,

        [Parameter()]
        [string]
        $ContinuationToken,

        [Parameter()]
        [string]
        $QueryOrder,

        [Parameter()]
        [string]
        $Path,

        [Parameter()]
        [string]
        $IsExactNameMatch,

        [Parameter()]
        [string]
        $TagFilter,

        [Parameter()]
        [string]
        $PropertyFilters,

        [Parameter()]
        [string]
        $DefinitionIdFilter,

        [Parameter()]
        [bool]
        $IsDeleted
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'release-definitions'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'GET'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat | Select-Object -ExpandProperty value
        If ($results.count -eq 0)
        {
            Return
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Get-APReleaseList.ps1
function Get-APReleaseList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline releases.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline releases based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER PropertyFilters
     
    A comma-delimited list of extended properties to retrieve.
 
    .PARAMETER TagFilter
     
    A comma-delimited list of tags. Only releases with these tags will be returned.
 
    .PARAMETER IsDeleted
     
    Gets the soft deleted releases, if true.
 
    .PARAMETER SourceBranchFilter
     
    Releases with given sourceBranchFilter will be returned.
 
    .PARAMETER ArtifactVersionId
     
    Releases with given artifactVersionId will be returned. E.g. in case of Build artifactType, it is buildId.
 
    .PARAMETER SourceId
     
    Unique identifier of the artifact used. e.g. For build it would be {projectGuid}:{BuildDefinitionId}, for Jenkins it would be {JenkinsConnectionId}:{JenkinsDefinitionId}, for TfsOnPrem it would be {TfsOnPremConnectionId}:{ProjectName}:{TfsOnPremDefinitionId}. For third-party artifacts e.g. TeamCity, BitBucket you may refer 'uniqueSourceIdentifier' inside vss-extension.json https://github.com/Microsoft/vsts-rm-extensions/blob/master/Extensions.
 
    .PARAMETER ArtifactTypeId
     
    Releases with given artifactTypeId will be returned. Values can be Build, Jenkins, GitHub, Nuget, Team Build (external), ExternalTFSBuild, Git, TFVC, ExternalTfsXamlBuild.
 
    .PARAMETER Expand
     
    The property that should be expanded in the list of releases.
 
    .PARAMETER ContinuationToken
     
    Gets the releases after the continuation token provided.
 
    .PARAMETER Top
     
    Number of releases to get. Default is 50.
 
    .PARAMETER QueryOrder
     
    Gets the results in the defined order of created date for releases. Default is descending.
 
    .PARAMETER MaxCreatedTime
 
    Releases that were created before this time.
 
    .PARAMETER MinCreatedTime
     
    Releases that were created after this time.
 
    .PARAMETER EnvironmentStatusFilter
     
    Undefined, see link for documentation
 
    .PARAMETER StatusFilter
     
    Releases that have this status.
 
    .PARAMETER CreatedBy
     
    Releases created by this user.
 
    .PARAMETER SearchText
     
    Releases with names starting with searchText.
 
    .PARAMETER DefinitionEnvironmentId
     
    Undefined, see link for documentation
 
    .PARAMETER DefinitionId
     
    Releases from this release definition Id.
 
    .PARAMETER ReleaseIdFilter
     
    A comma-delimited list of releases Ids. Only releases with these Ids will be returned.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines release(s)
 
    .EXAMPLE
 
    C:\PS> Get-APRelease -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter()]
        [string]
        $PropertyFilters,

        [Parameter()]
        [string]
        $TagFilter,

        [Parameter()]
        [bool]
        $IsDeleted,

        [Parameter()]
        [string]
        $SourceBranchFilter,

        [Parameter()]
        [string]
        $ArtifactVersionId,

        [Parameter()]
        [string]
        $SourceId,

        [Parameter()]
        [string]
        $ArtifactTypeId,

        [Parameter()]
        [string]
        [ValidateSet('approvals', 'artifacts', 'environments', 'manualInterventions', 'none', 'tags', 'variables')]
        $Expand,

        [Parameter()]
        [int]
        $ContinuationToken,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [string]
        [ValidateSet('ascending', 'descending')]
        $QueryOrder,

        [Parameter()]
        [datetime]
        $MaxCreatedTime,

        [Parameter()]
        [datetime]
        $MinCreatedTime,

        [Parameter()]
        [string]
        $EnvironmentStatusFilter,

        [Parameter()]
        [string]
        $StatusFilter,

        [Parameter()]
        [string]
        $CreatedBy,

        [Parameter()]
        [string]
        $SearchText,

        [Parameter()]
        [int]
        $DefinitionEnvironmentId,

        [Parameter()]
        [int]
        $DefinitionId,

        [Parameter()]
        [int]
        $ReleaseIdFilter
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'release-releases'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APRepository.ps1
function Get-APRepository
{
    <#
    .SYNOPSIS
 
    Returns an Azure Pipeline repository.
 
    .DESCRIPTION
 
    Returns an Azure Pipeline repository by repository id.
    The id can be retrieved by using Get-APRepositoryList.
    The id can be the guid or the name of the repository.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER RepositoryId
 
    The name or ID of the repository.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APRepository -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -RepositoryId 'myRepository'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/git/repositories/get%20repository?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [string]
        $RepositoryId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'git-repositoryId') -f $RepositoryId
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APRepositoryList.ps1
function Get-APRepositoryList
{
    <#
    .SYNOPSIS
 
    Returns a list Azure Pipeline repositories.
 
    .DESCRIPTION
 
    Returns a list Azure Pipeline repositories.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER IncludeLinks
 
    [optional] True to include reference links. The default value is false.
 
    .PARAMETER IncludeAllUrls
 
    [optional] True to include all remote URLs. The default value is false.
 
    .PARAMETER IncludeHidden
 
    [optional] True to include hidden repositories. The default value is false.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APRepositoryList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/git/repositories/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [bool]
        $IncludeLinks,

        [Parameter()]
        [bool]
        $IncludeAllUrls,

        [Parameter()]
        [bool]
        $IncludeHidden
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'git-repositories'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APSession.ps1
Function Get-APSession
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipelines PS session data.
 
    .DESCRIPTION
 
    Returns Azure Pipelines PS session data that has been stored in the users local application data.
    Use Save-APSession to persist the session data to disk.
    The sensetive data is returned encrypted.
 
    .PARAMETER Id
     
    Session id.
 
    .PARAMETER SessionName
     
    The friendly name of the session.
 
    .PARAMETER Path
     
    The path where session data will be stored, defaults to $Script:ModuleDataPath.
 
    .LINK
 
    Save-APSession
    Remove-APModuleData
 
    .INPUTS
 
    None. You cannot pipe objects to Get-APSession.
 
    .OUTPUTS
 
    PSObject. Get-APSession returns a PSObject that contains the following:
        Instance
        Collection
        PersonalAccessToken
 
    .EXAMPLE
 
    C:\PS> Get-APSession
 
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter(ParameterSetName = 'ById',
            ValueFromPipelineByPropertyName)]
        [int]
        $Id,

        [Parameter()]
        [string]
        $SessionName,

        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath
    )
    Process
    {
        $_sessions = @()
        If (Test-Path $Path)
        {
            $data = Get-Content -Path $Path -Raw | ConvertFrom-Json           
            Foreach ($_data in $data.SessionData)
            {
                $_object = New-Object -TypeName PSCustomObject -Property @{
                    Id         = $_data.Id
                    Instance   = $_data.Instance
                    Collection = $_data.Collection
                    Project    = $_data.Project
                    SessionName = $_data.SessionName
                    Version    = $_data.Version
                    Saved      = $_data.Saved
                }
                If ($_data.PersonalAccessToken)
                {
                    $_object | Add-Member -NotePropertyName 'PersonalAccessToken' -NotePropertyValue ($_data.PersonalAccessToken | ConvertTo-SecureString)
                }
                $_sessions += $_object
            }
        }
        If ($null -ne $Global:_APSessions)
        {
            Foreach($_memSession in $Global:_APSessions)
            {
                If ($_sessions.Id -contains $_memSession.Id)
                {
                    Continue
                }
                Else
                {
                    $_sessions += $_memSession
                }
            }
        }
        If ($PSCmdlet.ParameterSetName -eq 'ById')
        {
            $_sessions = $_sessions | Where-Object {$PSItem.Id -eq $Id}
        }
        If ($SessionName)
        {
            $_sessions = $_sessions | Where-Object {$PSItem.SessionName -eq $SessionName}
        }
        Return $_sessions
    }
}
# Get-APTarget.ps1
function Get-APTarget
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline deployment group target.
 
    .DESCRIPTION
 
    Returns Azure Pipeline deployment group target based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
 
    ID of the deployment target to return.
 
    .PARAMETER TargetID
 
    ID of the deployment target to return.
 
    .PARAMETER Expand
 
    Include these additional details in the returned objects.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines deployment group.
 
    .EXAMPLE
 
    C:\PS> Get-APTarget -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6 -TargetId 25
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/targets/get?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
                
        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupID,

        [Parameter(Mandatory)]
        [int]
        $TargetId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [ValidateSet('assignedRequest','capabilities','lastCompletedRequest','none')]
        [string]
        $Expand
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-targetId') -f $DeploymentGroupID, $TargetId
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APTargetList.ps1
function Get-APTargetList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline deployment group targets.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline deployment group targets based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
 
    ID of the deployment group.
 
    .PARAMETER Tags
 
    Get only the deployment targets that contain all these comma separted list of tags.
 
    .PARAMETER Name
 
    Name pattern of the deployment targets to return.
 
    .PARAMETER PartialNameMatch
 
    When set to true, treats name as pattern. Else treats it as absolute match. Default is false.
 
    .PARAMETER Expand
 
    Include these additional details in the returned objects.
     
    .PARAMETER AgentStatus
     
    Get only deployment targets that have this status.
     
    .PARAMETER AgentJobResult
 
    Get only deployment targets that have this last job result.
 
    .PARAMETER ContinuationToken
 
    Get deployment targets with names greater than this continuationToken lexicographically.
 
    .PARAMETER Top
 
    Maximum number of deployment targets to return. Default is 1000.
 
    .PARAMETER Enabled
 
    Get only deployment targets that are enabled or disabled. Default is 'null' which returns all the targets.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines deployment group.
 
    .EXAMPLE
 
    C:\PS> Get-APTargetList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/targets/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupID,

        [Parameter()]
        [string[]]
        $Tags,

        [Parameter()]
        [string]
        $Name,

        [Parameter()]
        [bool]
        $PartialNameMatch,

        [Parameter()]
        [ValidateSet('assignedRequest', 'capabilities', 'lastCompletedRequest', 'none')]
        [string]
        $Expand,
        
        [Parameter()]
        [ValidateSet('all', 'offline', 'online')]
        [string]
        $AgentStatus,

        [Parameter()]
        [ValidateSet('all', 'failed', 'neverDeployed', 'passed')]
        [string]
        $AgentJobResult,

        [Parameter()]
        [string]
        $ContinuationToken,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [bool]
        $Enabled
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {

        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-targets') -f $DeploymentGroupID
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APTaskGroupList.ps1
function Get-APTaskGroupList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline task groups.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline task groups based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER TaskGroupId
 
    Id of the task group.
 
    .PARAMETER Expanded
 
    'true' to recursively expand task groups. Default is 'false'.
 
    .PARAMETER TaskIdFilter
 
    Guid of the taskId to filter.
 
    .PARAMETER Deleted
 
   'true'to include deleted task groups. Default is 'false'.
 
    .PARAMETER Top
 
    Number of task groups to get.
 
    .PARAMETER ContinuationToken
 
    Gets the task groups after the continuation token provided.
 
    .PARAMETER QueryOrder
 
    Gets the results in the defined order. Default is 'CreatedOnDescending'.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APTaskGroupList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/azure/devops/distributedtask/taskgroups/list?view=azure-devops-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter()]
        [string]
        $TaskGroupId,

        [Parameter()]
        [bool]
        $Expanded,

        [Parameter()]
        [string]
        $TaskIdFilter,

        [Parameter()]
        [bool]
        $Deleted,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [string]
        $ContinuationToken,

        [Parameter()]
        [ValidateSet('createdOnAscending','createdOnDescending')]
        [string]
        $QueryOrder
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'taskgroup-taskgroups'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Get-APVariableGroup.ps1
function Get-APVariableGroup
{
    <#
    .SYNOPSIS
 
    Returns an Azure Pipeline variable group.
 
    .DESCRIPTION
 
    Returns an Azure Pipeline variable group by group id.
    The id can be retrieved by using Get-APVariableGroupList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER GroupId
 
    Id of the variable group.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Get-APVariableGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -GroupId 7
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/builds/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [string]
        $GroupId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {

        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-variablegroupId') -f $GroupId
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APVariableGroupList.ps1
function Get-APVariableGroupList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline variable groups.
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline variable groups based on a filter query.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER GroupName
     
    Name of variable group.
 
    .PARAMETER ActionFilter
     
    Action filter for the variable group. It specifies the action which can be performed on the variable groups.
 
    .PARAMETER Top
     
    Number of variable groups to get.
 
    .PARAMETER ContinuationToken
     
    Gets the releases after the continuation token provided.
 
    .PARAMETER QueryOrder
     
    Gets the results in the defined order. Default is 'IdDescending'.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines release definition(s)
 
    .EXAMPLE
 
    C:\PS> Get-APVariableGroupList -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/list?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter()]
        [string]
        $GroupName,

        [Parameter()]
        [string]
        [ValidateSet('manage', 'none', 'use')]
        $ActionFilter,

        [Parameter()]
        [int]
        $Top,

        [Parameter()]
        [int]
        $ContinuationToken,

        [Parameter()]
        [ValidateSet('idAscending', 'idDescending')]
        [string]
        $QueryOrder
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'distributedtask-variablegroups'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method     = 'GET'
            Uri        = $uri
            Credential = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat | Select-Object -ExpandProperty value
        If ($results.count -eq 0)
        {
            Return
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Install-APAgent.ps1
Function Install-APAgent {
    <#
    .SYNOPSIS
 
    Installs a Azure Pipelines agent on the server executing the function.
 
    .DESCRIPTION
 
    Installs a Azure Pipelines agent.
    The agent can be configured to listen to a pool or a deployment group.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Pool
 
    The pool name.
 
    .PARAMETER DeploymentGroupName
 
    The deployment group name.
 
    .PARAMETER DeploymentGroupTag
 
    The deployment group tags.
 
    .PARAMETER Platform
 
    Operating system platform.
 
    .PARAMETER PatAuthentication
     
    Authenticate with a personal access token.
 
    .PARAMETER IntegratedAuthentication
     
    Authenticate with a integrated credentials.
 
    .PARAMETER NegotiateAuthentication
     
    Authenticate with a negotiation, this requires a credential.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to authenticate.
     
    .PARAMETER WindowsLogonCredential
     
    Specifies a user account that will run the windows service.
 
    .PARAMETER AgentWorkingFolder
     
    Agent's working directory, this must be unique to the agent, defaults to '_work'.
 
    .PARAMETER RootAgentFolder
     
    The directory where the agent will be installed, defaults to 'Agents'.
 
    .INPUTS
 
    None. You cannot pipe objects to Install-APAgent.
 
    .OUTPUTS
 
    String. Install-APAgent returns log from configuration.
 
    .EXAMPLE
 
    C:\PS> Install-Agent -PatAuthentication -PersonalAccessToken 'myToken' -DeploymentGroupName 'Dev' -DeploymentGroupTag 'myTag' -Collection 'DefaultCollection' -TeamProject 'AzurePipelinesPS' -Platform 'Windows'
 
    .EXAMPLE
 
    C:\PS> Install-Agent -NegotiateAuthentication -Credential $pscredential -Pool 'Default' -Collection 'DefaultCollection' -TeamProject 'AzurePipelinesPS' -Platform 'Linux'
 
    .LINK
 
    https://docs.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=vsts
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory)]
        [uri]
        $Instance,

        [Parameter(Mandatory)]
        [string]
        $Collection,

        [Parameter(Mandatory)]
        [string]
        $Project,

        [Parameter(Mandatory)]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = "ByPatAuthenticationPool")]
        [Parameter(ParameterSetName = "ByPatAuthenticationDeploymentGroup")]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(Mandatory,
            ParameterSetName = "ByNegotiateAuthenticationPool")]
        [Parameter(Mandatory,
            ParameterSetName = "ByNegotiateAuthenticationDeploymentGroup")]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = "ByPatAuthenticationPool")]
        [Parameter(Mandatory,
            ParameterSetName = "ByIntegratedAuthenticationPool")]
        [Parameter(Mandatory,
            ParameterSetName = "ByNegotiateAuthenticationPool")]
        [string]
        $Pool,

        [Parameter()]
        [string]
        [Parameter(Mandatory,
            ParameterSetName = "ByPatAuthenticationDeploymentGroup")]
        [Parameter(Mandatory,
            ParameterSetName = "ByIntegratedAuthenticationDeploymentGroup")]
        [Parameter(Mandatory,
            ParameterSetName = "ByNegotiateAuthenticationDeploymentGroup")]
        $DeploymentGroupName,

        [Parameter()]
        [string[]]
        $DeploymentGroupTag,

        [Parameter(Mandatory)]
        [ValidateSet('Windows', 'ubuntu.16.04-x64', 'ubuntu.14.04-x64')]
        [string]
        $Platform,

        [Parameter(ParameterSetName = "ByPatAuthenticationPool")]
        [Parameter(ParameterSetName = "ByPatAuthenticationDeploymentGroup")]
        [switch]
        $PatAuthentication,

        [Parameter(ParameterSetName = "ByIntegratedAuthenticationPool")]
        [Parameter(ParameterSetName = "ByIntegratedAuthenticationDeploymentGroup")]
        [switch]
        $IntegratedAuthentication,

        [Parameter(ParameterSetName = "ByNegotiateAuthenticationPool")]
        [Parameter(ParameterSetName = "ByNegotiateAuthenticationDeploymentGroup")]
        [switch]
        $NegotiateAuthentication,

        [Parameter()]
        [pscredential]
        $WindowsLogonCredential,

        [Parameter()]
        [string]
        $AgentWorkingFolder = '_work',

        [Parameter()]
        [string]
        $RootAgentFolder = 'vstsAgents'
    )

    $arguments = @(
        "--unattended"
        "--projectName `"{0}`"" -f $Project
        "--url $Instance$Collection"
        "--work `"{0}`"" -f $AgentWorkingFolder
        "--runasservice"
    )
    If ($Pool) {
        $arguments += "--pool `"{0}`"" -f $Pool
    }
    If ($DeploymentGroupName) {
        Write-Verbose "Configuring agent for deployment group: [$DeploymentGroupName]"
        $arguments += "--deploymentGroup"
        $arguments += "--deploymentGroupName `"{0}`"" -f $DeploymentGroupName
        If ($DeploymentGroupTag) {
            Write-Verbose ("Adding the following deployment tags: [{0}]" -f ($DeploymentGroupTag -join ', '))
            $arguments += "--addDeploymentGroupTags"
            $arguments += ("--deploymentGroupTags `"{0}`"" -f ($DeploymentGroupTag -join ', '))
        }
    }
    If ($WindowsLogonCredential.UserName) {
        Write-Verbose "Configuring the target agent to use a windows logon account: [$($WindowsLogonCredential.Username)]"
        $arguments += ("--windowsLogonAccount {0}" -f $WindowsLogonCredential.UserName)
        $arguments += ("--windowsLogonPassword `"{0}`"" -f $WindowsLogonCredential.GetNetworkCredential().Password)
    }
    If ($PatAuthentication) {
        $plainTextPat = Unprotect-APSecurePersonalAccessToken -PersonalAccessToken $PersonalAccessToken
        If (-not($plainTextPat)) {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: A personal access Token is required to use PAT authentications" -ErrorAction Stop
        }
        Write-Verbose "Authenticating using [PAT]"
        $arguments += "--auth Pat"
        $arguments += "--token $plainTextPat"
    }
    If ($IntegratedAuthentication) {
        Write-Verbose "Authenticating using [Integrated]"
        $arguments += "--auth integrated"
    }
    If ($NegotiateAuthentication) {
        Write-Verbose "Authenticating using [Negotiate]"
        $arguments += "--auth negotiate"
        $arguments += ("--userName {0}" -f $Credential.UserName)
        $arguments += ("--password {0}" -f $Credential.GetNetworkCredential().Password)
    }
    If (-not (Test-Path "$env:SystemDrive\$RootAgentFolder")) {
        Write-Verbose ("Creating root agent path: [{0}\{1}]" -f $env:SystemDrive, $RootAgentFolder)
        $null = New-Item -ItemType Directory -Path "$env:SystemDrive\$RootAgentFolder"
    }
    Set-Location "$env:SystemDrive\$RootAgentFolder"
    for ($i = 1; $i -lt 100; $i++) {
        $destFolder = 'A' + $i.ToString()
        if (-not (Test-Path ($destFolder))) {
            Write-Verbose "Creating destination folder: [$destFolder]"
            $null = New-Item -ItemType Directory -Path $destFolder
            Set-Location $destFolder
            break
        }
    }
    # Download agent
    $agentZip = "$PWD\agent.zip"
    $DefaultProxy = [System.Net.WebRequest]::DefaultWebProxy
    $securityProtocol = @()
    $securityProtocol += [Net.ServicePointManager]::SecurityProtocol
    $securityProtocol += [Net.SecurityProtocolType]::Tls12
    [Net.ServicePointManager]::SecurityProtocol = $securityProtocol
    $WebClient = New-Object Net.WebClient
    $uri = Get-APAgentPackage -Platform $Platform -Instance $Instance -ApiVersion $ApiVersion
    If(-not($uri))
    {
        Write-Error "[$($MyInvocation.MyCommand.Name)]: Unable to locate package url!" -ErrorAction Stop
    }
    If ($DefaultProxy -and (-not $DefaultProxy.IsBypassed($uri))) {
        $WebClient.Proxy = New-Object Net.WebProxy($DefaultProxy.GetProxy($uri).OriginalString, $True)
    }
    Write-Verbose "Downloading agent package from: [$uri]"
    $WebClient.DownloadFile($uri, $agentZip)
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    Write-Verbose "Extracting agent package"
    [System.IO.Compression.ZipFile]::ExtractToDirectory( $agentZip, "$PWD")
    Remove-Item $agentZip
    
    Write-Verbose "Configuring agent: [$arguments]"

    # Configure agent
    $arguments += "--agent {0}-{1}" -f $env:COMPUTERNAME, $destFolder
    $startprocessSplat = @{
        NoNewWindow            = $true
        Wait                   = $true
        FilePath               = "$env:SystemDrive\$RootAgentFolder\$destFolder\config.cmd"
        ArgumentList           = $arguments
        WorkingDirectory       = "$env:SystemDrive\$RootAgentFolder\$destFolder"
        RedirectStandardError  = 'errorResults.log'
        RedirectStandardOutput = 'results.log'
    }
    Start-Process @startprocessSplat
    Get-Content .\results.log
    $errorResults = Get-Content .\errorResults.log
    If ($errorResults) {
        Write-Error $errorResults
    }
}

# Invoke-APRestMethod.ps1
function Invoke-APRestMethod
{
    <#
    .SYNOPSIS
 
    Invokes an Azure Pipelines PS rest method.
 
    .DESCRIPTION
 
    Invokes an Azure Pipelines PS rest method.
 
    .PARAMETER Method
     
    Specifies the method used for the web request.
 
    .PARAMETER Body
     
    Specifies the body of the request. The body is the content of the request that follows the headers.
 
    .PARAMETER ContentType
     
    Specifies the content type of the web request. If this parameter is omitted and the request method is POST, Invoke-RestMethod sets the content type to application/x-www-form-urlencoded. Otherwise, the content type is not specified in the call.
 
    .PARAMETER Uri
 
    Specifies the Uniform Resource Identifier (URI) of the Internet resource to which the web request is sent. This parameter supports HTTP, HTTPS, FTP, and FILE values.
 
    .PARAMETER UseBasicParsing
 
    This parameter has been deprecated. Beginning with PowerShell 6.0.0, all Web requests use basic parsing only.
 
    .PARAMETER PersonalAccessToken
 
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request. The default is the Personal Access Token if it is defined, otherwise it is the current user.
     
    .OUTPUTS
 
    System.Int64, System.String, System.Xml.XmlDocument, The output of the cmdlet depends upon the format of the content that is retrieved.
 
    .OUTPUTS
 
    PSObject, If the request returns JSON strings, Invoke-RestMethod returns a PSObject that represents the strings.
 
    .EXAMPLE
 
    C:\PS> Invoke-APRestMethod -Method PATCH -Body $Body -ContentType 'application/json' -Uri 'https://myproject.visualstudio.com/release/releases?api-version=5.0-preview.6'
 
    .LINK
 
    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-6
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]
        $Method,

        [Parameter()]
        [psobject]
        $Body,

        [Parameter(Mandatory)]
        [uri]
        $Uri,

        [Parameter()]
        [string]
        $ContentType,

        [Parameter()]
        [switch]
        $UseBasicParsing,

        [Parameter()]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    process
    {
        $invokeRestMethodSplat = @{
            ContentType     = $ContentType
            Method          = $Method
            UseBasicParsing = $true
            Uri             = $uri.AbsoluteUri
        }
        If($Body)
        {
            $invokeRestMethodSplat.Body = $Body | ConvertTo-Json -Depth 20 
        }
        $authenticatedRestMethodSplat = Set-APAuthenticationType -InputObject $invokeRestMethodSplat -Credential $Credential -PersonalAccessToken $PersonalAccessToken
        $results = Invoke-RestMethod @authenticatedRestMethodSplat
        Return $results
    }
    
    end
    {
    }
}

# New-APBuild.ps1
function New-APBuild
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipeline build.
 
    .DESCRIPTION
 
    Creates an Azure Pipeline build by build definition name.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Name
 
    The name of the build definition to queue.
 
    .PARAMETER IgnoreWarnings
 
    Undocumented.
 
    .PARAMETER CheckInTicket
 
    Undocumented.
 
    .PARAMETER SourceBuildId
 
    Undocumented.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build.
 
    .EXAMPLE
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/variablegroups/add?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter()]
        [bool]
        $IgnoreWarnings,

        [Parameter()]
        [string]
        $CheckInTicket,

        [Parameter()]
        [int]
        $SourceBuildId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
        
    process
    {
        $getAPBuildDefinitionListSplat = @{
            Collection = $Collection
            Instance = $Instance
            Project = $Project
            ApiVersion = $ApiVersion
            Name = $Name
        }
        If($Credential)
        {
            $getAPBuildDefinitionListSplat.Credential = $Credential
        }
        If($PersonalAccessToken)
        {
            $getAPBuildDefinitionListSplat.PersonalAccessToken = $PersonalAccessToken
        }
        $definition = Get-APBuildDefinitionList @getAPBuildDefinitionListSplat
        $body = @{
            definition = $definition
        }
        $apiEndpoint = Get-APApiEndpoint -ApiType 'build-builds'
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'POST'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body                = $body
            ContentType         = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# New-APRelease.ps1
function New-APRelease
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipeline release.
 
    .DESCRIPTION
 
    Creates an Azure Pipeline release by definition id.
    The id can be retrieved by using Get-APReleaseList.
 
  .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DefinitionId
 
    Sets definition Id to create a release.
 
    .PARAMETER BuildId
 
    Id of the build to use as the artifact source, defaults to the latest build id.
    The buildId parameter does not support releases with multiple artifacts.
 
    .PARAMETER Description
 
    Sets description to create a release.
 
    .PARAMETER Reason
 
    Sets reason to create a release.
 
    .PARAMETER ManualEnvironments
 
    Sets list of environments to manual as condition.
 
    .PARAMETER IsDraft
 
    Sets 'true' to create release in draft mode, 'false' otherwise, defaults to 'false'.
 
    .PARAMETER Variables
     
    Sets list of release variables to be overridden at deployment time.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines variable group.
 
    .EXAMPLE
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/variablegroups/add?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [int]
        $DefinitionId,

        [Parameter()]
        [int]
        $BuildId,

        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [ValidateSet('continuousIntegration', 'manual', 'none', 'pullRequest', 'schedule')]
        [string]
        $Reason,

        [Parameter()]
        [string[]]
        $ManualEnvironments,

        [Parameter()]
        [string]
        $IsDraft = $false,

        [Parameter()]
        [hashtable]
        $Variables
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
        
    process
    {
        $getAPReleaseDefinitionSplat = @{
            Collection   = $Collection
            Project      = $Project
            ApiVersion   = $ApiVersion
            Instance     = $Instance
            DefinitionId = $DefinitionId
        }
        If ($PersonalAccessToken)
        {
            $getAPReleaseDefinitionSplat.PersonalAccessToken = $PersonalAccessToken
        }
        If ($Credential)
        {
            $getAPReleaseDefinitionSplat.Credential = $Credential
        }
        $definition = Get-APReleaseDefinition @getAPReleaseDefinitionSplat
        $_artifacts = @()
        Foreach ($artifactSource in $Definition.artifacts)
        {
            $getAPBuildDefinitionSplat = @{
                Collection = $Collection
                Project    = $Project
                ApiVersion = $ApiVersion
                Instance   = $Instance
                Top        = 1
            }
            If ($BuildId)
            {
                $getAPBuildDefinitionSplat.BuildIds = $BuildId
            }
            else
            {
                $getAPBuildDefinitionSplat.Definitions = $artifactSource.definitionReference.definition.id            
            }
            If ($PersonalAccessToken)
            {
                $getAPReleaseDefinitionSplat.PersonalAccessToken = $PersonalAccessToken
            }
            If ($Credential)
            {
                $getAPReleaseDefinitionSplat.Credential = $Credential
            }
            $build = Get-APBuildList @getAPBuildDefinitionSplat
            $_artifacts += @{
                alias             = $artifactSource.alias
                instanceReference = @{
                    id   = $build.id
                    name = $build.buildNumber
                }
            }
        }
        $body = @{
            DefinitionId       = $DefinitionId
            Description        = $Description
            Reason             = $Reason
            ManualEnvironments = $ManualEnvironments
            isDraft            = $IsDraft
            artifacts          = $_artifacts
        }
        If ($Variables)
        {
            $_variables = @{}
            Foreach ($token in $Variables.Keys)
            {
                $_variables.$token = @{
                    Value = $Variables.$token
                }
            }
            $body.Variables = $_variables
        }
        $apiEndpoint = Get-APApiEndpoint -ApiType 'release-releases'
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'POST'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body                = $body
            ContentType         = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# New-APRepository.ps1
function New-APRepository
{
    <#
    .SYNOPSIS
 
    Creates and Azure Pipeline repository.
 
    .DESCRIPTION
 
    Creates and Azure Pipeline repository.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Name
 
    The name of the repository to create.
 
    .PARAMETER ParentRepository
     
    The parent repository.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> New-APRepository -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -Name 'myFirstRepository'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/azure/devops/git/repositories/create?view=azure-devops-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [string]
        $Name
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $getAPProjectListSplat = @{
            Collection = $Collection
            Instance = $Instance
            ApiVersion = $ApiVersion
        }
        If($PersonalAccessToken)
        {
            $getAPProjectListSplat.PersonalAccessToken = $PersonalAccessToken
        }
        If($Credential)
        {
            $getAPProjectListSplat.Credential = $Credential
        }
        $projectId = Get-APProjectList @getAPProjectListSplat | Where-Object {$PSItem.Name -eq $Project} | Select-Object -ExpandProperty 'id'
        $body = @{
            name = $Name
            project = @{
                id = $projectId
            }
        }
        $apiEndpoint = Get-APApiEndpoint -ApiType 'git-repositories'
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'POST'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body                = $body
            ContentType         = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# New-APSession.ps1
Function New-APSession
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipelines session.
 
    .DESCRIPTION
 
    Creates an Azure Pipelines session.
    Use Save-APSession to persist the session data to disk.
    Save the session to a variable to pass the session to other functions.
 
    .PARAMETER SessionName
     
    The friendly name of the session.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    The value for collection should be the name of your orginization. If you are using Team Services or TFS then the collection should be DefaultCollection.
    See example 1.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Version
     
    TFS version, this will provide the module with the api version mappings.
 
    .PARAMETER Name
     
    The friendly name of the mdoule data instance, configured by Save-APSession.
 
    .PARAMETER Path
     
    The path where module data will be stored, defaults to $Script:ModuleDataPath.
 
    .LINK
 
    Save-APSession
    Remove-APModuleData
 
    .INPUTS
 
    None. You cannot pipe objects to New-APSession.
 
    .OUTPUTS
 
    PSObject. New-APSession returns a PSObject that contains the following:
        Instance
        Collection
        PersonalAccessToken
 
    .EXAMPLE
 
    C:\PS> New-APSession
 
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]
        $SessionName,

        [Parameter(Mandatory)]
        [uri]
        $Instance,

        [Parameter(Mandatory)]
        [string]
        $Collection,

        [Parameter(Mandatory)]
        [string]
        $Project,

        [Parameter(Mandatory)]
        [ValidateSet('vNext', '2018 Update 2', '2018 RTW', '2017 Update 2', '2017 Update 1', '2017 RTW', '2015 Update 4', '2015 Update 3', '2015 Update 2', '2015 Update 1', '2015 RTW')]
        [string]
        $Version,       

        [Parameter()]
        [string]
        $PersonalAccessToken,
        
        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath
    )
    Process
    {
        $_sessions = Get-APSession
        $sessionCount = $_sessions.Id.count
        $_session = New-Object -TypeName PSCustomObject -Property @{
            Instance            = $Instance
            Collection          = $Collection
            Project             = $Project
            Version             = $Version
            SessionName         = $SessionName
            Id                  = $sessionCount++
        }
        If ($PersonalAccessToken)
        {
            $securedPat = (ConvertTo-SecureString -String $PersonalAccessToken -AsPlainText -Force)
            $_session | Add-Member -NotePropertyName 'PersonalAccessToken' -NotePropertyValue $securedPat
        }
        If($null -eq $Global:_APSessions)
        {
            $Global:_APSessions = @()
        }
        $Global:_APSessions += $_session
        Return $_session
    }
}

# Publish-APBuildDefinition.ps1
function Publish-APBuildDefinition
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipelines build definition.
 
    .DESCRIPTION
 
    Creates an Azure Pipelines build definition by a template.
    A template can be retrieved by Get-APBuildDefinition.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DefinitionToCloneId
 
    Undefinied, see link for documentation.
 
    .PARAMETER DefinitionToCloneRevision
 
    Undefinied, see link for documentation.
 
    .PARAMETER ValidateProcessOnly
 
    Undefinied, see link for documentation.
 
    .PARAMETER Template
 
    The template provided by Get-APBuildDefinition.
 
    .INPUTS
         
    PSObject, the template provided by Get-APBuildDefinition.
 
    .OUTPUTS
 
    PSobject, Azure Pipelines build.
 
    .EXAMPLE
 
    C:\PS> Publish-APBuildDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DefinitionObject $template
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/definitions/create?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter()]
        [int]
        $DefinitionToCloneId,

        [Parameter()]
        [int]
        $DefinitionToCloneRevision,

        [Parameter()]
        [bool]
        $ValidateProcessOnly,

        [Parameter()]
        [PSobject]
        $Template
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = $Template
        $apiEndpoint = Get-APApiEndpoint -ApiType 'build-definitions'
        $queryParameters = Set-APQueryParameters -InputObject $PSBoundParameters
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
            Query       = $queryParameters
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            ContentType = 'application/json'
            Body        = $body
            Method      = 'POST'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: returned nothing." -ErrorAction Stop
        }
        ElseIf ($results.value)
        {
            return $results.value
        }
        Else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Publish-APReleaseDefinition.ps1
function Publish-APReleaseDefinition
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipelines release definition.
 
    .DESCRIPTION
 
    Creates an Azure Pipelines release definition by using a template.
    The template can be retrieved by using Get-APReleaseDefinition.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Template
 
    The template provided by Get-APReleaseDefinition.
 
    .INPUTS
         
    PSObject, the template provided by Get-APReleaseDefinition.
 
    .OUTPUTS
 
    PSobject, Azure Pipelines build.
 
    .EXAMPLE
 
    C:\PS> Publish-APReleaseDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DefinitionObject $template
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/definitions/create?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter()]
        [PSobject]
        $Template
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = $Template
        $apiEndpoint = Get-APApiEndpoint -ApiType 'release-definitions'
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            ContentType = 'application/json'
            Body        = $body
            Method      = 'POST'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Remove-APBuildDefinition.ps1
function Remove-APBuildDefinition
{
    <#
    .SYNOPSIS
 
    Deletes an Azure Pipeline build definition.
 
    .DESCRIPTION
 
    Deletes an Azure Pipeline build definition by definition id.
    The id can be retrieved by using Get-APBuildDefinitionList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DefinitionId
     
    The ID of the definition to be deleted.
 
    .INPUTS
     
 
    .OUTPUTS
 
    None, Remove-APBuildDefinition returns nothing.
 
    .EXAMPLE
 
    C:\PS> Remove-APBuildDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DefinitionId 5
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/definitions/delete?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
                
        [Parameter(Mandatory)]
        [int]
        $DefinitionId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'build-definitionId') -f $DefinitionId
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'DELETE'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Remove-APDeploymentGroup.ps1
function Remove-APDeploymentGroup
{
    <#
    .SYNOPSIS
 
    Deletes an Azure Pipeline deployment group.
 
    .DESCRIPTION
 
    Deletes an Azure Pipeline deployment group by deployment group id.
    The id can be retrieved by using Get-APDeploymentGroupList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
     
    ID of the deployment group to be deleted.
 
    .INPUTS
     
 
    .OUTPUTS
 
    None, Remove-APDeploymentGroup returns nothing.
 
    .EXAMPLE
 
    C:\PS> Remove-APDeploymentGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/deploymentgroups/delete?view=vsts-rest-5.0#
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
                
        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-deploymentGroupId') -f $DeploymentGroupID
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method      = 'DELETE'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Remove-APReleaseDefinition.ps1
function Remove-APReleaseDefinition
{
    <#
    .SYNOPSIS
 
    Deletes an Azure Pipeline release definition.
 
    .DESCRIPTION
 
    Deletes an Azure Pipeline release definition by definition id.
    The id can be retrieved by using Get-APReleaseDefinitionList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DefinitionId
     
    The ID of the definition to be deleted.
 
    .INPUTS
     
 
    .OUTPUTS
 
    None, Remove-APReleaseDefinition returns nothing.
 
    .EXAMPLE
 
    C:\PS> Remove-APReleaseDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DefinitionId 5
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/definitions/delete?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $DefinitionId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'release-definitionId') -f $DefinitionId
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method      = 'DELETE'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Remove-APSession.ps1
Function Remove-APSession
{
    <#
    .SYNOPSIS
 
    Removes an Azure Pipelines PS session.
 
    .DESCRIPTION
 
    Removes an Azure Pipelines PS session.
    If the session is saved, it will be removed from the saved sessions as well.
 
    .PARAMETER Id
     
    Session id.
 
    .PARAMETER Path
     
    The path where session data will be stored, defaults to $Script:ModuleDataPath.
 
    .LINK
 
    Save-APSession
    Remove-APModuleData
 
    .INPUTS
 
    None. You cannot pipe objects to Remove-APSession.
 
    .OUTPUTS
 
    PSObject. Remove-APSession returns a PSObject that contains the following:
        Instance
        Collection
        PersonalAccessToken
 
    .EXAMPLE
 
    C:\PS> Remove-APSession
 
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory,
            ValueFromPipelineByPropertyName)]
        [int]
        $Id,
       
        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath  
    )
    Process
    {
        $sessions = Get-APSession -Id $Id
        Foreach($session in $sessions)
        {
            If ($session.Saved -eq $true)
            {
                $newData = @{SessionData = @()}
                $data = Get-Content -Path $Path -Raw | ConvertFrom-Json
                Foreach ($_data in $data.SessionData)
                {
                    If ($_data.Id -eq $session.Id)
                    {
                        Continue
                    }       
                    else
                    {
                        $newData.SessionData += $_data
                    }
                }
                $newData | Convertto-Json -Depth 5 | Out-File -FilePath $Path
            }
            $Global:_APSessions = $Global:_APSessions | Where-Object {$PSItem.Id -ne $session.Id}
        }
    }
}
# Remove-APTarget.ps1
function Remove-APTarget
{
    <#
    .SYNOPSIS
 
    Deletes an Azure Pipeline deployment group target.
 
    .DESCRIPTION
 
    Deletes an Azure Pipeline deployment group target by the deployment group id and the target id.
    The deployment group id can be retrieved by using Get-APDeploymentGroupList.
    The target id can be retrieved by using Get-APTargetList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
     
    ID of the deployment group in which deployment target is deleted.
 
    .PARAMETER TargetId
     
    ID of the deployment target to delete.
 
    .INPUTS
     
 
    .OUTPUTS
 
    None, Remove-APTarget returns nothing.
 
    .EXAMPLE
 
    C:\PS> Remove-APTarget -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6 -TargetId 25
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/targets/delete?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupId,

        [Parameter(Mandatory)]
        [int]
        $TargetId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-targetId') -f $DeploymentGroupID, $TargetId
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method      = 'DELETE'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Remove-APVariableGroup.ps1
function Remove-APVariableGroup
{
    <#
    .SYNOPSIS
 
    Deletes an Azure Pipeline variable group.
 
    .DESCRIPTION
 
    Deletes an Azure Pipeline variable group by group id.
    The id can be retrieved by using Get-APVariableGroupList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER GroupId
     
    The ID of the Group to be deleted.
 
    .INPUTS
     
 
    .OUTPUTS
 
    None, Remove-APVariableGroup returns nothing.
 
    .EXAMPLE
 
    C:\PS> Remove-APVariableGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -GroupId 5
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/Variable/Groups/delete?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $GroupId
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-variablegroupId') -f $GroupId
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method      = 'DELETE'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Save-APSession.ps1
Function Save-APSession
{
    <#
    .SYNOPSIS
 
    Saves an Azure Pipelines PS session to disk.
 
    .DESCRIPTION
 
    Saves an Azure Pipelines PS session to disk.
    The sensetive data is encrypted and stored in the users local application data.
    These saved sessions will be available next time the module is imported.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Path
     
    The path where session data will be stored, defaults to $Script:ModuleDataPath.
     
    .INPUTS
 
    None. You cannot pipe objects to Save-APSession.
 
    .OUTPUTS
 
    None. Save-APSession returns nothing.
 
    .EXAMPLE
     
    C:\PS> Save-APSession -Instance 'https://.dev.azure.com/' -Collection 'myOrganization'
 
    .EXAMPLE
 
    C:\PS> Save-APSession -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection'
 
    .EXAMPLE
 
    C:\PS> Save-APSession -PersonalAccessToken 'myPatToken'
 
    .LINK
 
    Get-APModuleData
    Remove-APModuleData
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter(Mandatory,
            ValueFromPipeline)]
        [object]
        $Session,
       
        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath        
    )
    Begin
    {
        If (-not(Test-Path $Path))
        {
            $data = @{SessionData = @()}
        }
        else 
        {
            $data = Get-Content -Path $Path -Raw | ConvertFrom-Json           
        }
    }
    Process
    {
        $_object = @{
            Version     = $Session.Version
            Instance    = $Session.Instance
            Id          = $Session.Id
            SessionName = $Session.SessionName
            Collection  = $Session.Collection
            Project     = $Session.Project
            Saved       = $true
        }
        If ($Session.PersonalAccessToken)
        {
            $_object.PersonalAccessToken = ($Session.PersonalAccessToken | ConvertFrom-SecureString) 
        }
        $data.SessionData += $_object
        $session | Remove-APSession -Path $Path
    }
    End
    {
        $data | Convertto-Json -Depth 5 | Out-File -FilePath $Path
        Write-Verbose "[$($MyInvocation.MyCommand.Name)]: [$SessionName]: Session data has been stored at [$Path]"
    }
}

# Update-APBuildDefinition.ps1
function Update-APBuildDefinition
{
    <#
    .SYNOPSIS
 
    Modifies an Azure Pipeline build definition.
 
    .DESCRIPTION
 
    Modifies an Azure Pipeline build definition by a template.
    A template can retrived by using Get-APBuildDefinition.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Template
 
    The template provided by Get-APBuildDefinition.
 
    .INPUTS
         
    PSObject, the template provided by Get-APBuildDefinition
 
    .OUTPUTS
 
    PSobject, Azure Pipelines build.
 
    .EXAMPLE
 
    C:\PS> Update-APBuildDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -Template $template
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/Build/definitions/update?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter()]
        [PSobject]
        $Template
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = $Template
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'build-definitionId') -f $body.Id
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            ContentType = 'application/json'
            Body        = $body
            Method      = 'PUT'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Update-APDeploymentGroup.ps1
function Update-APDeploymentGroup
{
    <#
    .SYNOPSIS
 
    Modifies an Azure Pipeline deployment group.
 
    .DESCRIPTION
 
    Modifies an Azure Pipeline deployment group by deployment group id.
    The id can be retrieved by using Get-APDeploymentGroupList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
     
    ID of the deployment.
 
    .PARAMETER Description
     
    Description of the deployment group.
  
    .PARAMETER Name
     
    Name of the deployment group.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSobject, An Azure Pipelines deployment group.
 
    .EXAMPLE
 
    C:\PS> Update-APDeploymentGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/deploymentgroups/delete?view=vsts-rest-5.0#
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupId,

        [Parameter()]
        [string]
        $Name,

        [Parameter()]
        [string]
        $Description
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = @{
            Name        = $Name
            Description = $Description
        }
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-deploymentGroupId') -f $DeploymentGroupID
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'PATCH'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body                = $body
            ContentType         = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Update-APReleaseDefinition.ps1
function Update-APReleaseDefinition
{
    <#
    .SYNOPSIS
 
    Modifies an Azure Pipeline release definition.
 
    .DESCRIPTION
 
    Modifies an Azure Pipeline release definition by a template.
    A template can retrived by using Get-APReleaseDefinition.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Template
 
    The template provided by Get-APReleaseDefinition.
 
    .INPUTS
         
    PSObject, the template provided by Get-APReleaseDefinition
 
    .OUTPUTS
 
    PSobject, Azure Pipelines build.
 
    .EXAMPLE
 
    C:\PS> Update-APReleaseDefinition -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -Template $template
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/definitions/update?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter()]
        [PSobject]
        $Template
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = $Template
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'release-definitionId') -f $body.Id
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            ContentType = 'application/json'
            Body        = $body
            Method      = 'PUT'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Return
        }
        ElseIf ($results.value)
        {
            Return $results.value
        }
        Else
        {
            Return $results
        }
    }
    
    end
    {
    }
}
# Update-APReleaseEnvironment.ps1
function Update-APReleaseEnvironment
{
    <#
    .SYNOPSIS
 
    Update the status of a release environment.
 
    .DESCRIPTION
 
    Update the status of a release environment by release id and environment id
    The release id can be retrieved by using Get-APReleaseList.
    The environment id can be retrieved by using Get-APRelease and providing the release id.
    The environment id is nested in the release object that is returned.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER ReleaseID
     
    Id of the release.
 
    .PARAMETER EnvironmentID
     
    Id of the release environment.
 
    .PARAMETER Comment
     
    Comment used for the release status change.
     
    .PARAMETER ScheduledDeploymentTime
     
    Scheduled deployment time.
     
    .PARAMETER Status
     
    Environment status.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Release Environment
 
    .EXAMPLE
 
    C:\PS> Update-APReleaseEnvironment -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -ReleaseId 3 -EnvironmentId 8099
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/release/releases/update%20release%20environment?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $ReleaseId,

        [Parameter(Mandatory)]
        [int]
        $EnvironmentId,

        [Parameter()]
        [string]
        $Comment, 

        [Parameter()]
        [string]
        $ScheduledDeploymentTime,

        [Parameter(Mandatory)]
        [string]
        [ValidateSet('canceled', 'inProgress', 'notStarted', 'partiallySucceeded', 'queued', 'rejected', 'scheduled', 'succeeded', 'undefined')]
        $Status
    )

    
    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = @{
            status = $Status
        }
        if ($Comment)
        {
            $body.comment = $Comment
        }
        If ($ScheduledDeploymentTime)
        {
            $body.scheduledDeploymentTime = $ScheduledDeploymentTime
        }
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'release-environmentId') -f $ReleaseId, $EnvironmentId
        [uri] $uri = Set-APUri -Instance $Instance -Collection $Collection -Project $Project -ApiEndpoint $apiEndpoint -ApiVersion $ApiVersion
        $invokeAPRestMethodSplat = @{
            ContentType         = 'application/json'
            Method              = 'PATCH'
            Body                = $body
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
        }
        Invoke-APRestMethod @invokeAPRestMethodSplat
    }
    
    end
    {
    }
}
# Update-APTarget.ps1
function Update-APTarget
{
    <#
    .SYNOPSIS
 
    Modifies an Azure Pipeline deployment group target.
 
    .DESCRIPTION
 
    Modifies an Azure Pipeline deployment group target.
    The deployment group id can be retrieved by using Get-APDeploymentGroupList.
    The target id can be retrieved by using Get-APTargetList.
 
    .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
     
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER DeploymentGroupId
     
    ID of the deployment.
 
    .PARAMETER Id
     
    Identifier of the deployment target.
  
    .PARAMETER Tags
     
    Tags for the deployment target.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSobject, An Azure Pipelines deployment group target.
 
    .EXAMPLE
 
    C:\PS> Update-APDeploymentGroup -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject' -DeploymentGroupID 6 -Id 30 -Tags 'myFirstTag', 'mySecondTag'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/targets/update?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,
        
        [Parameter(Mandatory)]
        [int]
        $DeploymentGroupId,

        [Parameter(Mandatory)]
        [int]
        $Id,

        [Parameter(Mandatory)]
        [string[]]
        $Tags
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        $body = @{
            Tags = ($Tags -join ',')
            Id   = $Description
        }
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-targets') -f $DeploymentGroupID
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method      = 'PATCH'
            Uri         = $uri
            Credential  = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body        = $body
            ContentType = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Update-APVariableGroup.ps1
function Update-APVariableGroup
{
    <#
    .SYNOPSIS
 
    Modifies an Azure Pipeline variable group.
 
    .DESCRIPTION
 
    Modifies an Azure Pipeline variable group by group id.
    The id can be retrieved by using Get-APVariableGroupList.
 
  .PARAMETER Instance
     
    The Team Services account or TFS server.
     
    .PARAMETER Collection
     
    For Azure DevOps the value for collection should be the name of your orginization.
    For both Team Services and TFS The value should be DefaultCollection unless another collection has been created.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER PersonalAccessToken
     
    Personal access token used to authenticate that has been converted to a secure string.
    It is recomended to uses an Azure Pipelines PS session to pass the personal access token parameter among funcitons, See New-APSession.
    https://docs.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=vsts
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .PARAMETER GroupId
 
    Id of the variable group.
 
    .PARAMETER Session
 
    Azure DevOps PS session, created by New-APSession.
 
    .PARAMETER Description
     
    Sets description of the variable group.
  
    .PARAMETER Name
     
    Sets name of the variable group.
 
    .PARAMETER Variables
     
    Sets variables contained in the variable group.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines variable group.
 
    .EXAMPLE
 
    $varibales = @{
        Var1 = 'updated val1'
        Var2 = 'updated val2'
        Var3 = 'updated val3'
    }
    $updateAPVariableGroupSplat = @{
        Description = 'my updated variable group'
        Name = 'myUpdatedVariableGroup'
        Variables = $varibales
        Instance = 'https://myproject.visualstudio.com'
        Collection = 'DefaultCollection'
        Project = 'myFirstProject'
        GroupId = 2
    }
    Update-APVariableGroup @updateAPVariableGroupSplat
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/distributedtask/variablegroups/update?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'ByPersonalAccessToken')]
    Param
    (
        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [uri]
        $Instance,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Collection,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $Project,

        [Parameter(Mandatory,
            ParameterSetName = 'ByPersonalAccessToken')]
        [Parameter(Mandatory,
            ParameterSetName = 'ByCredential')]
        [string]
        $ApiVersion,

        [Parameter(ParameterSetName = 'ByPersonalAccessToken')]
        [Security.SecureString]
        $PersonalAccessToken,

        [Parameter(ParameterSetName = 'ByCredential')]
        [pscredential]
        $Credential,

        [Parameter(Mandatory,
            ParameterSetName = 'BySession')]
        [object]
        $Session,

        [Parameter(Mandatory)]
        [int]
        $GroupId,

        [Parameter(Mandatory)]
        [string]
        $Name,

        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [object]
        $Variables
    )

    begin
    {
        If ($PSCmdlet.ParameterSetName -eq 'BySession')
        {
            $currentSession = $Session | Get-APSession
            If ($currentSession)
            {
                $Instance = $currentSession.Instance
                $Collection = $currentSession.Collection
                $Project = $currentSession.Project
                $ApiVersion = (Get-APApiVersion -Version $currentSession.Version)
                $PersonalAccessToken = $currentSession.PersonalAccessToken
            }
        }
    }
    
    process
    {
        If($Variables.GetType().Name -eq 'hashtable')
        {
            $_variables = @{}
            Foreach ($token in $Variables.Keys)
            {
                $_variables.$token = @{
                    Value = $Variables.$token
                }
            }
        }
        else 
        {
            $_variables = $Variables    
        }
        $body = @{
            Name        = $Name
            Description = $Description
            Type        = 'Vsts'
            Variables   = $_variables
        }
        $apiEndpoint = (Get-APApiEndpoint -ApiType 'distributedtask-VariableGroupId') -f $GroupId
        $setAPUriSplat = @{
            Collection  = $Collection
            Instance    = $Instance
            Project     = $Project
            ApiVersion  = $ApiVersion
            ApiEndpoint = $apiEndpoint
        }
        [uri] $uri = Set-APUri @setAPUriSplat
        $invokeAPRestMethodSplat = @{
            Method              = 'PUT'
            Uri                 = $uri
            Credential          = $Credential
            PersonalAccessToken = $PersonalAccessToken
            Body                = $body
            ContentType         = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Imported from [D:\_work\1\s\AzurePipelinesPS\Tests]