AzurePipelinesPS.psm1

$Script:PSModuleRoot = $PSScriptRoot
$Script:ModuleName = "AzurePipelinesPS"
$Script:ModuleData = (Join-Path -Path $env:APPDATA -ChildPath $Script:ModuleName)
$Script:ModuleDataPath = (Join-Path -Path $Script:ModuleData -ChildPath "DefaultServer.xml")
# 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 = (Get-APModuleData).Instance,

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

        [Parameter()]
        [string]
        $Version = (Get-APModuleData).Version,

        [Parameter()]
        [pscredential]
        $Credential
    )
    Begin
    {
    }
    Process
    {

        Switch ($Version)
        {
            'VNext'
            {
                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.
    This function will return the api endpoint for that api type provided.
 
    .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-release'
            {
                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}'
            }
            default
            {
                Write-Error "[$($MyInvocation.MyCommand.Name)]: [$ApiType] is not supported" -ErrorAction Stop
            }
        }
    }

    end
    {
    }
}

# Get-APApiVersion.ps1
function Get-APApiVersion
{    
    <#
    .SYNOPSIS
 
    Returns the api version availalbe for the TFS version provided.
 
    .DESCRIPTION
 
    Returns the api version availalbe for the TFS version provided.
    This is based on the TFS version stored in module data, use 'Set-APModuleData -Version' to populate the moduledata.
 
    .PARAMETER Version
     
    TFS version, this will provide the module with the api version mappings.
 
    .OUTPUTS
 
    String, The api version availalbe 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 = (Get-APModuleData).Version
    )

    begin
    {
    }

    process
    {
        Switch ($Version)
        {
            'vNext'
            {
                Return '5.0-preview.1'
            }
            '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 'Set-APModuleData -Version' to populate module data. " -ErrorAction Stop
            }
        }
    }

    end
    {
    }
}

# Get-APSecurePersonalAccessToken.ps1
Function Get-APSecurePersonalAccessToken
{
    <#
    .SYNOPSIS
 
    Returns decrypted personal access token that is stored in the module data.
 
    .DESCRIPTION
 
    Returns decrypted personal access token that is stored in the module data.
 
    .PARAMETER Path
     
    The path where module data will be stored, defaults to $Script:ModuleDataPath.
         
    .OUTPUTS
 
    String, unsecure personal access token.
 
    .EXAMPLE
 
    C:\PS> Get-SecurePersonalAccessToken
 
    .EXAMPLE
 
    C:\PS> Get-SecurePersonalAccessToken -Path $path
 
    .LINK
 
    https://docs.microsoft.com/en-us/azure/devops/integrate/get-started/authentication/authentication-guidance?view=vsts
    #>


    [CmdletBinding()]
    Param
    (
        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath   
    )
    Process
    {
        $moduleData = Get-APModuleData
        If($moduleData.PersonalAccessToken)
        {
            $BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($moduleData.PersonalAccessToken)
            $plainText = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
        }
        else
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: Personal access token data was not found: [$Path], run 'Set-APModuleData -PersonalAccessToken' to populate the module data." -ErrorAction Stop
        }
        Return $plainText
    }
}

# 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 module data, unless a credential is supplied to the function.
 
    .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()]
        [pscredential]
        $Credential
    )

    begin
    {
    }

    process
    {
        $moduleData = Get-APModuleData
        If ($Credential)
        {
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Authenticating with the provided credential."
            $InputObject.Credential = $Credential
        }
        ElseIf ($moduleData.PersonalAccessToken)
        {
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Authenticating with the stored personal access token."
            $PersonalAccessTokenToken = Get-APSecurePersonalAccessToken
            $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',
            '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 = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

        [Parameter()]
        [string]
        $Project,

        [Parameter()]
        [string]
        $Query,

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion)
    )

    begin
    {
    }

    process
    {   
        If($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 -eq '5.0-preview.1') -and $Query)
        {
            # Append .vsrm prefix to instance if the api version is VNext and the api endpoint matches release
            [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 -match 'release') -and ($ApiVersion -eq '5.0-preview.1'))
        {
            # Append .vsrm prefix to instance if the api version is VNext and the api endpoint matches release
            [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 $ApiEndpoint)
        {
            [uri] $output = '{0}{1}' -f $Instance.AbsoluteUri, $ApiEndpoint
        }
    }

    end
    {
        Return $output
    }
}


# 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
     
    The value for collection should be DefaultCollection for both Team Services and TFS.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .PARAMETER Description
     
    Description of the deployment group.
  
    .PARAMETER Name
     
    Name of the deployment group.
     
    .PARAMETER PoolId
     
    Identifier of the deployment pool in which deployment agents are registered.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [string]
        $PoolId,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
            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 on a filter query.
 
    .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 BuildId
 
    The ID of the build
 
    .PARAMETER PropertyFilters
     
    Undocumented
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $PropertyFilters,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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(s).
 
    .DESCRIPTION
 
    Returns Azure Pipeline build definitions(s) based on a filter query, if one is not provided the default will return all available definitions for the project provided.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Revision,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $MinMetricsTime,
       
        [Parameter(ParameterSetName = 'ByQuery')]
        [string[]]
        $PropertyFilters,

        [Parameter(ParameterSetName = 'ByQuery')]
        [switch]
        $IncludeLatestBuilds,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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(s).
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline build definitions(s) based on a filter query, if one is not provided the default will return all available definitions for the project provided.
 
    .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 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.
 
    .PARAMETER ApiVersion
 
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $TaskIdFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $IncludeLatestBuilds,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $IncludeAllProperties,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $NotBuiltAfter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $BuiltAfter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $Path,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int[]]
        $DefinitionIds,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $MinMetricsTime,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ContinuationToken,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Top,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $RepositoryType,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $RepositoryId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $Name,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $YamlFilename,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: Unable to locate build." -ErrorAction Stop
        }
        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, if one is not provided the default will return all available builds for the project provided.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $RepositoryId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int[]]
        $BuildIds,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $BranchName,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ContinuationToken,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Top,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string[]]
        $Properties,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string[]]
        $TagFilters,

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

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $RequestedFor,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $MaxTime,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $MinTime,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $BuildNumber,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int[]]
        $Queues,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int[]]
        $Definitions,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $RepositoryType,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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 based on a filter query.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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 group(s).
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline deployment group(s) based on a filter query.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $Name,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Top,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int[]]
        $Ids,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APModuleData.ps1
Function Get-APModuleData
{
    <#
    .SYNOPSIS
 
    Returns module data that has been stored in the users local application data by Set-APModuleData.
 
    .DESCRIPTION
 
    Returns module data that has been stored in the users local application data by Set-APModuleData.
    The sensetive data is returned still encrypted.
     
    .PARAMETER Path
     
    The path where module data is stored, defaults to $Script:ModuleDataPath
 
    .LINK
 
    Set-APModuleData
    Remove-APModuleData
 
    .INPUTS
 
    None. You cannot pipe objects to Get-APModuleData.
 
    .OUTPUTS
 
    PSObject. Get-APModuleData returns a PSObject that contains the following:
        Instance
        Collection
        PersonalAccessToken
 
    .EXAMPLE
 
    C:\PS> Get-APModuleData
 
    #>

    [CmdletBinding()]
    Param
    (
        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath
    )
    Process
    {
        If (Test-Path $Path)
        {
            $moduleData = Import-Clixml -Path $Path -ErrorAction Stop
        }
        else
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: Module data was not found: [$Path]! Run 'Set-APModuleData' to populate module data." -ErrorAction Stop
        }
        $moduleData = @{
            Instance            = $moduleData.Instance
            Collection          = $moduleData.Collection
            PersonalAccessToken = $moduleData.PersonalAccessToken
            Version             = $moduleData.Version
        }
        Write-Output -InputObject $moduleData
    }
}

# Get-APQueue.ps1
Function Get-APQueue
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline queue(s).
 
    .DESCRIPTION
 
    Returns Azure Pipeline queue(s) based on a filter query.
 
    .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 QueueName
 
    Filters queues whose names start with this prefix.
 
    .PARAMETER ActionFilter
 
    Filter Queues based on the permission mentioned.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $QueueName,

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )
    Begin
    {
    }
    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
        }
        $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(s).
 
    .DESCRIPTION
 
    Returns Azure Pipeline release(s) based on a filter query, if one is not provided the default will return the top 50 releases for the project provided.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ApprovalFilters,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $PropertyFilters,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $TopGateRecords,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APReleaseDefinition.ps1
function Get-APReleaseDefinition
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline release definition(s).
 
    .DESCRIPTION
 
    Returns Azure Pipeline release definitions(s) based on a filter query, if one is not provided the default will return the top 50 releases for the project provided.
 
    .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 DefinitionId
     
    Releases with names starting with searchText.
 
    .PARAMETER PropertyFilters
     
    The property that should be expanded in the list of releases.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string[]]
        $PropertyFilters,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.count -eq 0)
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: Unable to locate release." -ErrorAction Stop
        }
        ElseIf ($results.value)
        {
            return $results.value
        }
        Else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APReleaseDefinitionList.ps1
function Get-APReleaseDefinitionList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline release definition(s).
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline release definitions(s) based on a filter query, if one is not provided the default will return the top 50 releases for the project provided.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $SearchText,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ArtifactType,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $Top,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ContinuationToken,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $QueryOrder,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $Path,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $IsExactNameMatch,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $TagFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $PropertyFilters,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $DefinitionIdFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $IsDeleted,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat | Select-Object -ExpandProperty value
        If ($results.count -eq 0)
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: Unable to locate release." -ErrorAction Stop
        }
        Else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APReleaseList.ps1
function Get-APReleaseList
{
    <#
    .SYNOPSIS
 
    Returns a list of Azure Pipeline release(s).
 
    .DESCRIPTION
 
    Returns a list of Azure Pipeline release(s) based on a filter query, if one is not provided the default will return the top 50 releases for the project provided.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $PropertyFilters,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $TagFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $IsDeleted,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $SourceBranchFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ArtifactVersionId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $SourceId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ArtifactTypeId,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $ContinuationToken,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Top,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $MaxCreatedTime,

        [Parameter(ParameterSetName = 'ByQuery')]
        [datetime]
        $MinCreatedTime,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $EnvironmentStatusFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $StatusFilter,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $CreatedBy,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $SearchText,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $DefinitionEnvironmentId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $DefinitionId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $ReleaseIdFilter,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    process
    {
        $apiEndpoint = Get-APApiEndpoint -ApiType 'release-release'
        $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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# 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
     
    The value for collection should be DefaultCollection for both Team Services and TFS.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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
     
    The value for collection should be DefaultCollection for both Team Services and TFS.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string[]]
        $Tags,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $Name,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $PartialNameMatch,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $ContinuationToken,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Top,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $Enabled,        

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Get-APVariableGroup.ps1
function Get-APVariableGroup
{
    <#
    .SYNOPSIS
 
    Returns an Azure Pipeline variable group(s).
 
    .DESCRIPTION
 
    Returns an Azure Pipeline variable group(s) based on a filter query, if one is not provided the default will return all available builds for the project provided.
 
    .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 GroupId
 
    Id of the variable group.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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
     
    The value for collection should be DefaultCollection for both Team Services and TFS.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .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'.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $GroupName,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $Top,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $ContinuationToken,

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat | Select-Object -ExpandProperty value
        If ($results.count -eq 0)
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)]: Unable to locate the variable group." -ErrorAction Stop
        }
        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
     
    The value for collection should be DefaultCollection for both Team Services and TFS.
 
    .PARAMETER Project
     
    Project ID or project name.
 
    .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. 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 = "Default")]
    param
    (
        [Parameter()]
        [string]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [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(ParameterSetName = "ByPatAuthenticationPool")]
        [Parameter(ParameterSetName = "ByPatAuthenticationDeploymentGroup")]
        [string]
        $PersonalAccessToken,

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

        [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) {
        $PersonalAccessToken = Get-APSecurePersonalAccessToken
        If (-not($PersonalAccessToken)) {
            Write-Error "A PAT Token is required to use PAT authentications, use 'Set-TFSServer -PAT' to store your token securely" -ErrorAction Stop
        }
        Write-Verbose "Authenticating using [PAT]"
        $arguments += "--auth Pat"
        $arguments += "--token $PersonalAccessToken"
    }
    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 
    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-APBuild.ps1
function Invoke-APBuild
{
    <#
    .SYNOPSIS
 
    Returns Azure Pipeline build(s).
 
    .DESCRIPTION
 
    Returns Azure Pipeline build(s) based on a filter query, if one is not provided the default will return all available builds for the project provided.
 
    .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 Name
     
    Name of the build.
 
    .PARAMETER IgnoreWarnings
 
    Undocumented.
 
    .PARAMETER CheckInTicket
 
    Undocumented.
 
    .PARAMETER SourceBuildId
 
    Undocumented.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .INPUTS
     
 
    .OUTPUTS
 
    PSObject, Azure Pipelines build(s)
 
    .EXAMPLE
 
    C:\PS> Invoke-APBuild -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection' -Project 'myFirstProject'
 
    .LINK
 
    https://docs.microsoft.com/en-us/rest/api/vsts/build/builds/queue?view=vsts-rest-5.0
    #>

    [CmdletBinding(DefaultParameterSetName = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $IgnoreWarnings,

        [Parameter(ParameterSetName = 'ByQuery')]
        [string]
        $CheckInTicket,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $SourceBuildId,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    process
    {
        $getAPBuildDefinitionList = @{
            Collection = $Collection
            Project    = $Project
            ApiVersion = $ApiVersion
            Instance   = $Instance
            Credential = $Credential
            Name       = $Name
        }
        $build = Get-APBuildDefinitionList @getAPBuildDefinitionList

        $body = @{
            definition = $build
        }
        $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      = 'POST'
            Uri         = $uri
            Credential  = $Credential           
            Body        = $body
            ContentType = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Invoke-APRestMethod.ps1
function Invoke-APRestMethod
{
    <#
    .SYNOPSIS
 
    Invokes Azure DevOps Pipelines rest method.
 
    .DESCRIPTION
 
    Invokes Azure DevOps Pipelines 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 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()]
        [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
        $results = Invoke-RestMethod @authenticatedRestMethodSplat
        Return $results
    }
    
    end
    {
    }
}

# Publish-APBuildDefinition.ps1
function Publish-APBuildDefinition
{
    <#
    .SYNOPSIS
 
    Creates an Azure Pipelines build definition.
 
    .DESCRIPTION
 
    Creates an Azure Pipelines build definition with the output of Format-APTemplate.
 
    .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 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 the Format-APTemplate function.
 
    .PARAMETER ApiVersion
 
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .INPUTS
         
    PSObject, the template provided by the Format-APTemplate function.
 
    .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 = 'Default')]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $DefinitionToCloneId,

        [Parameter(ParameterSetName = 'ByQuery')]
        [int]
        $DefinitionToCloneRevision,

        [Parameter(ParameterSetName = 'ByQuery')]
        [bool]
        $ValidateProcessOnly,

        [Parameter(ParameterSetName = 'ByTemplate')]
        [PSobject]
        $Template,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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 with the output of Format-APTemplate.
 
    .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 Template
 
    The template provided by the Format-APTemplate function.
 
    .PARAMETER ApiVersion
 
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .INPUTS
         
    PSObject, the template provided by the Format-APTemplate function.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [Parameter()]
        [PSobject]
        $Template,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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
    {
    }
}
# 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 the Get-APBuildDefinitionList -Name.
 
    .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 DefinitionId
     
    The ID of the definition to be deleted.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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.
 
    .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 DeploymentGroupId
     
    ID of the deployment group to be deleted.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Remove-APModuleData.ps1
Function Remove-APModuleData
{
    <#
    .SYNOPSIS
 
    Removes module data that has been stored in the users local application data by Set-APModuleData.
 
    .DESCRIPTION
 
    Removes module data that has been stored in the users local application data by Set-APModuleData.
    The type of data removed depends on the parameters supplied to Remove-APModuleData.
     
    .LINK
 
    Get-APModuleData
    Set-APModuleData
 
    .PARAMETER Instance
     
    Remove instance from module data
 
    .PARAMETER Collection
     
    Remove collection from module data
     
    .PARAMETER PersonalAccessToken
     
    Remove personal access token from module data
 
    .PARAMETER Version
     
    TFS version, this will provide the module with the api version mappings.
     
    .PARAMETER Path
     
    The path where module data will be stored, defaults to $Script:ModuleDataPath
 
    .INPUTS
 
    None. You cannot pipe objects to Remove-ModuleData.
 
    .OUTPUTS
 
    None. Remove-ModuleData returns nothing.
 
    .EXAMPLE
 
    C:\PS> Remove-ModuleData -Instance
 
    .EXAMPLE
 
    C:\PS> Remove-ModuleData -Collection -PersonalAccessToken
    #>

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

        [Parameter()]
        [Switch]
        $Collection,

        [Parameter()]
        [Switch]
        $PersonalAccessToken,

        [Parameter()]
        [Switch]
        $Version,

        [Parameter()]
        [string]
        $Path = $Script:ModuleDataPath   
    )
    Process
    {
        $export = $false
        $moduleData = Get-APModuleData -Path $Path
        If ($Instance.IsPresent)
        {
            $moduleData.Instance = $null
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Instance has been removed."
            $export = $true
        } 
        If ($Collection.IsPresent)
        {
            $moduleData.Collection = $null
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Collection has been removed."
            $export = $true
        }       
        If ($PersonalAccessToken.IsPresent)
        {
            $moduleData.PersonalAccessToken = $null
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: PersonalAccessToken has been removed."
            $export = $true
        }
        If ($Version.IsPresent)
        {
            $moduleData.Version = $null
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Version has been removed."
            $export = $true
        }
        If (($Collection.IsPresent + $PersonalAccessToken.IsPresent + $Instance.IsPresent + $Version.IsPresent) -eq 0)
        {
            $moduleData.Instance = $null
            $moduleData.Collection = $null
            $moduleData.PersonalAccessToken = $null
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Removing all module data."
        }
        If ($export)
        {
            $moduleData | Export-Clixml -Path $Path  -Force
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Module data has been updated: [$Path]"    
        }
    }
}

# 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 the Get-APReleaseDefinitionList -Name.
 
    .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 DefinitionId
     
    The ID of the definition to be deleted.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Remove-APTarget.ps1
function Remove-APTarget
{
    <#
    .SYNOPSIS
 
    Deletes an Azure Pipeline deployment group.
 
    .DESCRIPTION
 
    Deletes an Azure Pipeline deployment group.
 
    .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 DeploymentGroupId
     
    ID of the deployment group in which deployment target is deleted.
 
    .PARAMETER TargetId
     
    ID of the deployment target to delete.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $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 the Get-APVariableGroupList function.
 
    .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 GroupId
     
    The ID of the Group to be deleted.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($results.value)
        {
            return $results.value
        }
        else
        {
            return $results
        }
    }
    
    end
    {
    }
}
# Set-APModuleData.ps1
Function Set-APModuleData
{
    <#
    .SYNOPSIS
 
    Generate module data used to set static values for certian parameters.
 
    .DESCRIPTION
 
    Generate module data used to set static values for certian parameters.
    The sensetive data is encrypted and stored in the users local application data.
 
    .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 PersonalAccessToken
     
    Personal access token used to authenticate. 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 Path
     
    The path where module data will be stored, defaults to $Script:ModuleDataPath.
     
    .INPUTS
 
    None. You cannot pipe objects to Set-APModuleData.
 
    .OUTPUTS
 
    None. Set-APModuleData returns nothing.
 
    .EXAMPLE
     
    C:\PS> Set-APModuleData -Instance 'https://.dev.azure.com/' -Collection 'myOrganization'
 
    .EXAMPLE
 
    C:\PS> Set-APModuleData -Instance 'https://myproject.visualstudio.com' -Collection 'DefaultCollection'
 
    .EXAMPLE
 
    C:\PS> Set-APModuleData -PersonalAccessToken 'myPatToken'
 
    .LINK
 
    Get-APModuleData
    Remove-APModuleData
    #>


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

        [Parameter()]
        [string]
        $Collection,

        [Parameter()]
        [string]
        $PersonalAccessToken,

        [Parameter()]
        [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]
        $Path = $Script:ModuleDataPath        
    )
    Process
    {
        $export = $false
        If (-not($Script:ModuleDataPath))
        {
            Write-Error "[$($MyInvocation.MyCommand.Name)] requires the global variable ModuleData that is populated during module import, please import the module." -ErrorAction Stop
        }
        If (-not(Test-Path $Path))
        {
            $null = New-Item -Path $Path -ItemType File -Force
            $null = Export-Clixml -Path $Path -InputObject @{}
        }
        $moduleData = Get-APModuleData -Path $Path
        If ($Instance)
        {
            If (-not($Instance.IsAbsoluteUri))
            {
                Write-Error "[$($MyInvocation.MyCommand.Name)]: [$Instance] is not a valid uri" -ErrorAction Stop
            }
            $moduleData.Instance = $Instance.AbsoluteUri
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Instance has been set to [$($Instance.AbsoluteUri)]"
            $export = $true
        }        
        If ($PersonalAccessToken)
        {
            $securedPat = (ConvertTo-SecureString -String $PersonalAccessToken -AsPlainText -Force)
            $moduleData.PersonalAccessToken = $securedPat
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: PersonalAccessToken has been set"
            $export = $true
        }
        If ($Collection)
        {
            $moduleData.Collection = $Collection
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Collection has been set to [$Collection]"
            $export = $true
        }
        If ($Version)
        {
            $moduleData.Version = $Version
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Version has been set to [$Version]"
            $export = $true
        }
        If ($export)
        {
            $moduleData | Export-Clixml -Path $Path  -Force
            Write-Verbose "[$($MyInvocation.MyCommand.Name)]: Module data has been stored: [$PathPath]"
        }
    }
}

# Update-APDeploymentGroup.ps1
function Update-APDeploymentGroup
{
    <#
    .SYNOPSIS
 
    Modifies an Azure Pipeline deployment group.
 
    .DESCRIPTION
 
    Modifies an Azure Pipeline deployment group.
 
    .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 DeploymentGroupId
     
    ID of the deployment.
 
    .PARAMETER Description
     
    Description of the deployment group.
  
    .PARAMETER Name
     
    Name of the deployment group.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

        [Parameter()]
        [string]
        $Name,

        [Parameter()]
        [string]
        $Description,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
            Body        = $body
            ContentType = 'application/json'
        }
        $results = Invoke-APRestMethod @invokeAPRestMethodSplat 
        If ($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.
 
    .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 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.
 
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

        [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,

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    
    begin
    {
    }
    
    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
        }
        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.
 
    .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 DeploymentGroupId
     
    ID of the deployment.
 
    .PARAMETER Id
     
    Identifier of the deployment target.
  
    .PARAMETER Tags
     
    Tags for the deployment target.
  
    .PARAMETER ApiVersion
     
    Version of the api to use.
 
    .PARAMETER Credential
 
    Specifies a user account that has permission to send the request.
 
    .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()]
    Param
    (
        [Parameter()]
        [uri]
        $Instance = (Get-APModuleData).Instance,

        [Parameter()]
        [string]
        $Collection = (Get-APModuleData).Collection,

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

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

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

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

        [Parameter()]
        [string]
        $ApiVersion = (Get-APApiVersion), 

        [Parameter()]
        [pscredential]
        $Credential
    )

    begin
    {
    }
    
    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
            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]