ADOPS.psm1

#region GitAccessLevels

[Flags()] enum AccessLevels {
    Administer              = 1
    GenericRead             = 2
    GenericContribute       = 4
    ForcePush               = 8
    CreateBranch            = 16
    CreateTag               = 32
    ManageNote              = 64
    PolicyExempt            = 128
    CreateRepository        = 256
    DeleteRepository        = 512
    RenameRepository        = 1024
    EditPolicies            = 2048
    RemoveOthersLocks       = 4096
    ManagePermissions       = 8192
    PullRequestContribute   = 16384
    PullRequestBypassPolicy = 32768
}
#endregion GitAccessLevels

#region SkipTest

class SkipTest : Attribute {
    [string[]]$TestNames

    SkipTest([string[]]$Name)
    {
        $this.TestNames = $Name
    }
}
#endregion SkipTest

#region GetADOPSHeader

function GetADOPSHeader {
    [CmdletBinding()]
    param (
        [string]$Organization
    )

    $Res = @{}

    if ($script:ADOPSCredentials.Count -eq 0) {
        throw 'No ADOPS credentials found. Have you used Connect-ADOPS to log in?'
    }

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $HeaderObj = $Script:ADOPSCredentials[$Organization]
        $res.Add('Organization', $Organization)
    }
    else {
        $r = $script:ADOPSCredentials.Keys | Where-Object {$script:ADOPSCredentials[$_].Default -eq $true}
        $HeaderObj = $script:ADOPSCredentials[$r]
        $res.Add('Organization', $r)
    }

    $UserName = $HeaderObj.Credential.UserName
    $Password = $HeaderObj.Credential.GetNetworkCredential().Password

    $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $UserName, $Password)))
    $Header = @{
        Authorization = ("Basic {0}" -f $base64AuthInfo)
    }

    $Res.Add('Header',$Header)

    $Res
}
#endregion GetADOPSHeader

#region InvokeADOPSRestMethod

function InvokeADOPSRestMethod {
    param (
        [Parameter(Mandatory)]
        [URI]$Uri,

        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod]$Method,

        [Parameter()]
        [string]$Body,

        [Parameter()]
        [string]$Organization,

        [Parameter()]
        [string]$ContentType = 'application/json',

        [Parameter()]
        [switch]$FullResponse,

        [Parameter()]
        [string]$OutFile
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $CallHeaders = GetADOPSHeader -Organization $Organization
    }
    else {
        $CallHeaders = GetADOPSHeader
    }

    $InvokeSplat = @{
        'Uri' = $Uri
        'Method' = $Method
        'Headers' = $CallHeaders.Header
        'ContentType' = $ContentType
    }

    if (-not [string]::IsNullOrEmpty($Body)) {
        $InvokeSplat.Add('Body', $Body)
    }

    if ($FullResponse) {
        $InvokeSplat.Add('ResponseHeadersVariable', 'ResponseHeaders')
        $InvokeSplat.Add('StatusCodeVariable', 'ResponseStatusCode')
    }

    if ($OutFile) {
        Invoke-RestMethod @InvokeSplat -OutFile $OutFile
    }
    else {
        $Result = Invoke-RestMethod @InvokeSplat

        if ($Result -like "*Azure DevOps Services | Sign In*") {
            throw 'Failed to call Azure DevOps API. Please login before using.'
        }
        elseif ($FullResponse) {
            @{ Content = $Result; Headers = $ResponseHeaders; StatusCode = $ResponseStatusCode }
        }
        else {
            $Result
        }
    }
}
#endregion InvokeADOPSRestMethod

#region Connect-ADOPS

function Connect-ADOPS {
    [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSAvoidUsingConvertToSecureStringWithPlainText', '')]
    [CmdletBinding(DefaultParameterSetName = 'PAT')]
    param (
        [Parameter(ParameterSetName = 'PAT', Mandatory)]
        [string]$Username,
        
        [Parameter(ParameterSetName = 'PAT', Mandatory)]
        [string]$PersonalAccessToken,

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

        [Parameter(ParameterSetName = 'PSCredential', Mandatory)]
        [Parameter(ParameterSetName = 'PAT', Mandatory)]
        [string]$Organization,

        [Parameter(ParameterSetName = 'PSCredential')]
        [Parameter(ParameterSetName = 'PAT')]
        [switch]$Default
    )
    
    if ($PSCmdlet.ParameterSetName -eq 'PAT') {
        $Credential = [pscredential]::new($Username, (ConvertTo-SecureString -String $PersonalAccessToken -AsPlainText -Force))
    }
    $ShouldBeDefault = $Default.IsPresent

    if ($script:ADOPSCredentials.Count -eq 0) {
        $ShouldBeDefault = $true
        $Script:ADOPSCredentials = @{}
    }
    else {
        $CurrentDefault = $script:ADOPSCredentials.Keys | Where-Object { $ADOPSCredentials[$_].Default -eq $true }
        if ($CurrentDefault -eq $Organization) {
            # If we are overwriting current default it should stay default regardless of -Default parameter.
            $ShouldBeDefault = $true
        }
        elseif ($Default.IsPresent) {
            # We are adding a new default, remove the current.
            $ADOPSCredentials[$CurrentDefault].Default = $false
        }
    }

    $OrgData = @{
        Credential = $Credential
        Default    = $ShouldBeDefault
    }
    
    $Script:ADOPSCredentials[$Organization] = $OrgData
    
    $URI = "https://vssps.dev.azure.com/$Organization/_apis/profile/profiles/me?api-version=7.1-preview.3"

    try {
        InvokeADOPSRestMethod -Method Get -Uri $URI
    }
    catch {
        $Script:ADOPSCredentials.Remove($Organization)
        throw $_
    }
}
#endregion Connect-ADOPS

#region Disconnect-ADOPS

function Disconnect-ADOPS {
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization
    )

    # Only require $Organization if several connections
    if ($Script:ADOPSCredentials.Count -eq 0) {
        throw "There are no current connections!"
    } # Allow not specifying organization if there's only one connection
    elseif ($Script:ADOPSCredentials.Count -eq 1 -and [string]::IsNullOrWhiteSpace($Organization)) {
        $Script:ADOPSCredentials = @{}
        # Make sure to exit script after clearing hashtable
        return
    }
    elseif (-not $Script:ADOPSCredentials.ContainsKey($Organization)) {
        throw "No connection made for organization $Organization!"
    }

    # If the connection to be removed is set as default, set another one
    $ChangeDefault = $Script:ADOPSCredentials[$Organization].Default
    
    $Script:ADOPSCredentials.Remove($Organization)

    # If there are any connections left and we removed the default
    if ($Script:ADOPSCredentials.Count -gt 0 -and $ChangeDefault) {
        # Set another one to default
        $Name = ($Script:ADOPSCredentials.GetEnumerator() | Select-Object -First 1).Name
        $Script:ADOPSCredentials[$Name].Default = $true
    }
}
#endregion Disconnect-ADOPS

#region Get-ADOPSAuditActions

function Get-ADOPSAuditActions {
    param (
        [Parameter()]
        [string]$Organization
    )
    
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    } else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    (InvokeADOPSRestMethod -Uri "https://auditservice.dev.azure.com/$Organization/_apis/audit/actions" -Method Get).value
}
#endregion Get-ADOPSAuditActions

#region Get-ADOPSConnection

function Get-ADOPSConnection {
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization
    )
    
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Script:ADOPSCredentials.GetEnumerator() | Where-Object { $_.Key -eq $Organization}
    }
    else {
        $Script:ADOPSCredentials
    }
}
#endregion Get-ADOPSConnection

#region Get-ADOPSElasticPool

function Get-ADOPSElasticPool {
    [CmdletBinding()]
    param (
        [Parameter()]
        [int32]$PoolId,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    } else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    if ($PSBoundParameters.ContainsKey('PoolId')) {
        $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/elasticpools/$PoolId?api-version=7.1-preview.1"
    } else {
        $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/elasticpools?api-version=7.1-preview.1"
    }
    
    $Method = 'GET'
    $ElasticPoolInfo = InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization -Body $Body
    if ($ElasticPoolInfo.psobject.properties.name -contains 'value') {
        Write-Output $ElasticPoolInfo.value
    } else {
        Write-Output $ElasticPoolInfo
    }
}
#endregion Get-ADOPSElasticPool

#region Get-ADOPSFileContent

function Get-ADOPSFileContent {
    param (
        [Parameter()]
        [string]$Organization,

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

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

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

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    } else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    if (-Not $FilePath.StartsWith('/')) {
        $FilePath = $FilePath.Insert(0, '/')
    }

    $UrlEncodedFilePath = [System.Web.HttpUtility]::UrlEncode($FilePath)
    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/git/repositories/$RepositoryId/items?path=$UrlEncodedFilePath&api-version=7.0"

    InvokeADOPSRestMethod -Uri $Uri -Method Get
}
#endregion Get-ADOPSFileContent

#region Get-ADOPSGroup

function Get-ADOPSGroup {
    param ([Parameter()]
        [string]$Organization,

        [Parameter(DontShow)]
        [string]$ContinuationToken
    )
    
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    
    if (-not [string]::IsNullOrEmpty($ContinuationToken)) {
        $Uri = "https://vssps.dev.azure.com/$Organization/_apis/graph/groups?continuationToken=$ContinuationToken&api-version=7.1-preview.1"
    }
    else {
        $Uri = "https://vssps.dev.azure.com/$Organization/_apis/graph/groups?api-version=7.1-preview.1"
    }
    
    $Method = 'GET'

    $Response = (InvokeADOPSRestMethod -FullResponse -Uri $Uri -Method $Method -Organization $Organization)

    $Groups = $Response.Content.value
    Write-Verbose "Found $($Response.Content.count) groups"

    if($Response.Headers.ContainsKey('X-MS-ContinuationToken')) {
        Write-Verbose "Found continuationToken. Will fetch more groups."
        $parameters = [hashtable]$PSBoundParameters
        $parameters.Add('ContinuationToken', $Response.Headers['X-MS-ContinuationToken']?[0])
        $Groups += Get-ADOPSGroup @parameters
    }
    
    Write-Output $Groups
}
#endregion Get-ADOPSGroup

#region Get-ADOPSNode

function Get-ADOPSNode {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [int32]$PoolId,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    } else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/elasticpools/$PoolId/nodes?api-version=7.1-preview.1"

    $Method = 'GET'
    $NodeInfo = InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization

    if ($NodeInfo.psobject.properties.name -contains 'value') {
        Write-Output $NodeInfo.value
    } else {
        Write-Output $NodeInfo
    }
}
#endregion Get-ADOPSNode

#region Get-ADOPSPipeline

function Get-ADOPSPipeline {
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

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

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/pipelines?api-version=7.1-preview.1"
    
    $InvokeSplat = @{
        Method       = 'Get'
        Uri          = $URI
        Organization = $Organization
    }

    $AllPipelines = (InvokeADOPSRestMethod @InvokeSplat).value

    if ($PSBoundParameters.ContainsKey('Name')) {
        $Pipelines = $AllPipelines | Where-Object {$_.name -eq $Name}
        if (-not $Pipelines) {
            throw "The specified PipelineName $Name was not found amongst pipelines: $($AllPipelines.name -join ', ')!" 
        } 
    } else {
        $Pipelines = $AllPipelines
    }

    $return = @()

    foreach ($Pipeline in $Pipelines) {

        $InvokeSplat = @{
            Method       = 'Get'
            Uri          = $Pipeline.url
            Organization = $Organization
        }
    
        $result = InvokeADOPSRestMethod @InvokeSplat

        $return += $result
    }

    return $return
}

#endregion Get-ADOPSPipeline

#region Get-ADOPSPipelineTask

function Get-ADOPSPipelineTask {
    param (
        [Parameter()]
        [string]$Name,

        [Parameter()]
        [string]$Organization,

        [Parameter()]
        [int]$Version
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Uri =  "https://dev.azure.com/$Organization/_apis/distributedtask/tasks?api-version=7.1-preview.1"

    $result = InvokeADOPSRestMethod -Uri $Uri -Method Get

    $ReturnValue = $result | ConvertFrom-Json -AsHashtable | Select-Object -ExpandProperty value

    if (-Not [string]::IsNullOrEmpty($Name)) {
        $ReturnValue = $ReturnValue |  Where-Object -Property name -EQ $Name
    }
    if ($Version) {
        $ReturnValue = $ReturnValue |  Where-Object -FilterScript {$_.version.major -eq $Version}
    }

    $ReturnValue
}
#endregion Get-ADOPSPipelineTask

#region Get-ADOPSPool

function Get-ADOPSPool {
    [CmdletBinding(DefaultParameterSetName = 'All')]
    param (
        [Parameter(Mandatory, ParameterSetName = 'PoolId')]
        [int32]$PoolId,

        [Parameter(Mandatory, ParameterSetName = 'PoolName')]
        [string]$PoolName,

        # Include legacy pools
        [Parameter(ParameterSetName = 'All')]
        [switch]$IncludeLegacy,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    switch ($PSCmdlet.ParameterSetName) {
        'PoolId' { $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/pools/$PoolId`?api-version=7.1-preview.1" }
        'PoolName' { $uri = "https://dev.azure.com/$Organization/_apis/distributedtask/pools?poolName=$PoolName`&api-version=7.1-preview.1" }
        'All' { $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/pools?api-version=7.1-preview.1" }
    }
    
    $Method = 'GET'
    $PoolInfo = InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization

    if ($PoolInfo.psobject.properties.name -contains 'value') {
        $PoolInfo = $PoolInfo.value
    }
    if ((-not ($IncludeLegacy.IsPresent)) -and $PSCmdlet.ParameterSetName -eq 'All') {
        $PoolInfo = $PoolInfo | Where-Object { $_.IsLegacy -eq $false }
    }
    Write-Output $PoolInfo
}
#endregion Get-ADOPSPool

#region Get-ADOPSProject

function Get-ADOPSProject {
    [CmdletBinding()]
    param (
        [Parameter()]
        [string]$Project,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/_apis/projects?api-version=7.1-preview.4"

    $Method = 'GET'
    $ProjectInfo = (InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization).value

    if (-not [string]::IsNullOrWhiteSpace($Project)) {
        $ProjectInfo = $ProjectInfo | Where-Object -Property Name -eq $Project
    }

    Write-Output $ProjectInfo
}
#endregion Get-ADOPSProject

#region Get-ADOPSRepository

function Get-ADOPSRepository {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$Project,

        [Parameter()]
        [string]$Repository,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    if ($PSBoundParameters.ContainsKey('Repository')) {
        $Uri = "https://dev.azure.com/$Organization/$Project/_apis/git/repositories/$Repository`?api-version=7.1-preview.1"
    }
    else {
        $Uri = "https://dev.azure.com/$Organization/$Project/_apis/git/repositories?api-version=7.1-preview.1"
    }
    
    $result = InvokeADOPSRestMethod -Uri $Uri -Method Get -Organization $Organization

    if ($result.psobject.properties.name -contains 'value') {
        Write-Output -InputObject $result.value
    }
    else {
        Write-Output -InputObject $result
    }
}
#endregion Get-ADOPSRepository

#region Get-ADOPSServiceConnection

function Get-ADOPSServiceConnection {
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

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

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization
    )
    
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/serviceendpoint/endpoints?api-version=7.1-preview.4"
    
    $InvokeSplat = @{
        Method       = 'Get'
        Uri          = $URI
        Organization = $Organization
    }

    $AllPipelines = (InvokeADOPSRestMethod @InvokeSplat).value

    if ($PSBoundParameters.ContainsKey('Name')) {
        $Pipelines = $AllPipelines | Where-Object {$_.name -eq $Name}
        if (-not $Pipelines) {
            throw "The specified ServiceConnectionName $Name was not found amongst Connections: $($AllPipelines.name -join ', ')!" 
        } 
    } else {
        $Pipelines = $AllPipelines
    }

    return $Pipelines

}
#endregion Get-ADOPSServiceConnection

#region Get-ADOPSUsageData

function Get-ADOPSUsageData {
    param(
        [Parameter()]
        [ValidateSet('Private','Public')]
        [string]$ProjectVisibility = 'Public',

        [Parameter()]
        [Switch]$SelfHosted,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    if ($SelfHosted.IsPresent) {
        $Hosted = $false
    }
    else {
        $Hosted = $true
    }

    $URI = "https://dev.azure.com/$Organization/_apis/distributedtask/resourceusage?parallelismTag=${ProjectVisibility}&poolIsHosted=${Hosted}&includeRunningRequests=true"
    $Method = 'Get'
    
    $InvokeSplat = @{
        Method       = $Method
        Uri          = $URI
        Organization = $Organization
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion Get-ADOPSUsageData

#region Get-ADOPSUser

function Get-ADOPSUser {
    [CmdletBinding(DefaultParameterSetName = 'Default')]
    param (
        [Parameter(Mandatory, ParameterSetName = 'Name', Position = 0)]
        [string]$Name,

        [Parameter(Mandatory, ParameterSetName = 'Descriptor', Position = 0)]
        [string]$Descriptor,

        [Parameter()]
        [string]$Organization,

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

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    if ($PSCmdlet.ParameterSetName -eq 'Default') {
        $Uri = "https://vssps.dev.azure.com/$Organization/_apis/graph/users?api-version=6.0-preview.1"
        $Method = 'GET'
        if(-not [string]::IsNullOrEmpty($ContinuationToken)) {
            $Uri += "&continuationToken=$ContinuationToken"
        }
        $Response = (InvokeADOPSRestMethod -FullResponse -Uri $Uri -Method $Method -Organization $Organization)
        $Users = $Response.Content.value
        Write-Verbose "Found $($Response.Content.count) users"

        if($Response.Headers.ContainsKey('X-MS-ContinuationToken')) {
            Write-Verbose "Found continuationToken. Will fetch more users."
            $parameters = [hashtable]$PSBoundParameters
            $parameters.Add('ContinuationToken', $Response.Headers['X-MS-ContinuationToken']?[0])
            $Users += Get-ADOPSUser @parameters
        }   
        Write-Output $Users
    }
    elseif ($PSCmdlet.ParameterSetName -eq 'Name') {
        $Uri = "https://vsaex.dev.azure.com/$Organization/_apis/UserEntitlements?`$filter=name eq '$Name'&`$orderBy=name Ascending&api-version=6.0-preview.3"
        $Method = 'GET'
        $Users = (InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization).members.user
        Write-Output $Users
    }
    elseif ($PSCmdlet.ParameterSetName -eq 'Descriptor') {
        $Uri = "https://vssps.dev.azure.com/$Organization/_apis/graph/users/$Descriptor`?api-version=6.0-preview.1"
        $Method = 'GET'
        $User = (InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization)
        Write-Output $User
    }
}
#endregion Get-ADOPSUser

#region Get-ADOPSWiki

function Get-ADOPSWiki {
    param (
        [Parameter(Mandatory)]
        [string]$Project,

        [Parameter()]
        [string]$WikiId,

        [Parameter()]
        [string]$Organization
    )
 
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    $BaseUri = "https://dev.azure.com/$Organization/$Project/_apis/wiki/wikis"
    
    if ($WikiId) {
        $Uri = "${BaseUri}/${WikiId}?api-version=7.1-preview.2"
    }
    else {
        $Uri = "${BaseUri}?api-version=7.1-preview.2"
    }

    $Method = 'Get'

    $res = InvokeADOPSRestMethod -Uri $URI -Method $Method -Organization $Organization
    
    if ($res.psobject.properties.name -contains 'value') {
        Write-Output -InputObject $res.value
    }
    else {
        Write-Output -InputObject $res
    }
}
#endregion Get-ADOPSWiki

#region Import-ADOPSRepository

function Import-ADOPSRepository {
    [CmdLetBinding(DefaultParameterSetName='RepositoryName')]
    param (
        [Parameter(Mandatory)]
        [string]$GitSource,

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

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

        [Parameter()]
        [string]$Organization,

        [Parameter()]
        [switch]$Wait
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    switch ($PSCmdlet.ParameterSetName) {
        'RepositoryName' { $RepoIdentifier = $RepositoryName}
        'RepositoryId'   { $RepoIdentifier = $RepositoryId}
        Default {}
    }
    $InvokeSplat = @{
        URI = "https://dev.azure.com/$Organization/$Project/_apis/git/repositories/$RepoIdentifier/importRequests?api-version=7.1-preview.1"
        Method = 'Post'
        Body = "{""parameters"":{""gitSource"":{""url"":""$GitSource""}}}"
        Organization = $Organization
    }

    $repoImport = InvokeADOPSRestMethod @InvokeSplat

    if ($PSBoundParameters.ContainsKey('Wait')) {
        # There appears to be a bug in this API where sometimes you don't get the correct status Uri back. Fix it by constructing a correct one instead.
        $verifyUri = "https://dev.azure.com/$Organization/$Project/_apis$($repoImport.url.Split('_apis')[1])"
        while ($repoImport.status -ne 'completed') {
            $repoImport = InvokeADOPSRestMethod -Uri $verifyUri -Method Get
            Start-Sleep -Seconds 1
        }
    }

    $repoImport
}
#endregion Import-ADOPSRepository

#region Invoke-ADOPSRestMethod

function Invoke-ADOPSRestMethod {
    [SkipTest('HasOrganizationParameter')]
    param (
        [Parameter(Mandatory)]
        [string]$Uri,

        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod]$Method = 'Get',

        [Parameter()]
        [string]$Body
    )

    $InvokeSplat = @{
        Uri = $Uri
        Method = $Method
    }

    if (-Not [String]::IsNullOrEmpty($Body)) {
        $InvokeSplat.Add('Body', $Body)
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion Invoke-ADOPSRestMethod

#region New-ADOPSAuditStream

function New-ADOPSAuditStream {
    [CmdletBinding(DefaultParameterSetName = 'AzureMonitorLogs')]
    param (
        [Parameter()]
        [string]$Organization,

        [Parameter(Mandatory, ParameterSetName = 'AzureMonitorLogs')]
        [ValidatePattern('^[a-fA-F0-9]{8}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{12}$', ErrorMessage = 'WorkspaceId should be in GUID format.')]
        [string]$WorkspaceId,

        [Parameter(Mandatory, ParameterSetName = 'AzureMonitorLogs')]
        [string]$SharedKey,

        [Parameter(Mandatory, ParameterSetName = 'Splunk')]
        [ValidatePattern('^(http|HTTP)[sS]?:\/\/', ErrorMessage = 'SplunkUrl must start with http:// or https://')]
        [string]$SplunkUrl,

        [Parameter(Mandatory, ParameterSetName = 'Splunk')]
        [ValidatePattern('^[a-fA-F0-9]{8}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{4}\-[a-fA-F0-9]{12}$', ErrorMessage = 'SplunkEventCollectorToken should be in GUID format.')]
        [string]$SplunkEventCollectorToken,

        [Parameter(Mandatory, ParameterSetName = 'AzureEventGrid')]
        [ValidatePattern('^(http|HTTP)[sS]?:\/\/', ErrorMessage = 'EventGridTopicHostname must start with http:// or https://')]
        [string]$EventGridTopicHostname,

        [Parameter(Mandatory, ParameterSetName = 'AzureEventGrid')]
        [ValidatePattern('^[A-Za-z0-9+\/]*={0,2}$', ErrorMessage = 'EventGridTopicAccessKey should be Base64 encoded')]
        [string]$EventGridTopicAccessKey
    )
    
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    } else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Body = switch ($PSCmdlet.ParameterSetName) {
        'AzureMonitorLogs' { 
            [ordered]@{
                consumerType = 'AzureMonitorLogs'
                consumerInputs = [Ordered]@{
                    WorkspaceId = $WorkspaceId
                    SharedKey = $SharedKey
                }
            } | ConvertTo-Json -Compress
         }
        'Splunk' { 
            [ordered]@{
                consumerType = 'Splunk'
                consumerInputs = [Ordered]@{
                    SplunkUrl = $SplunkUrl
                    SplunkEventCollectorToken = $SplunkEventCollectorToken
                }
            } | ConvertTo-Json -Compress
         }
        'AzureEventGrid' { 
            [ordered]@{
                consumerType = 'AzureEventGrid'
                consumerInputs = [ordered]@{
                    EventGridTopicHostname = $EventGridTopicHostname
                    EventGridTopicAccessKey = $EventGridTopicAccessKey
                }
            } | ConvertTo-Json -Compress
         }
    }
    $InvokeSplat = @{
        Uri = "https://auditservice.dev.azure.com/$Organization/_apis/audit/streams?api-version=7.1-preview.1"
        Method = 'Post'
        Body = $Body
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSAuditStream

#region New-ADOPSBuildPolicy

function New-ADOPSBuildPolicy {
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Project,

        [Parameter()]
        [string]$Organization,

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

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Branch,

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

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Displayname,

        [Parameter()]
        [string[]]$filenamePatterns
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    if (-Not ($Branch -match '^\w+/\w+/\w+$')) {
        $Branch = "refs/heads/$Branch"
    }
    $GitBranchRef = $Branch

    $settings = [ordered]@{
        scope = @(
            [ordered]@{
                repositoryId = $RepositoryId
                refName = $GitBranchRef
                matchKind = "exact"
            }
        )
        buildDefinitionId = $PipelineId.ToString()
        queueOnSourceUpdateOnly = $false
        manualQueueOnly = $false
        displayName = $Displayname
        validDuration = "0"
    }

    if ($filenamePatterns.Count -gt 0) {
        $settings.Add('filenamePatterns', $filenamePatterns)
    }

    $Body = [ordered]@{
        type = [ordered]@{
            id = "0609b952-1397-4640-95ec-e00a01b2c241" 
        }
        isBlocking = $true
        isEnabled = $true
        settings = $settings
    } 
    
    $Body = $Body | ConvertTo-Json -Depth 10 -Compress
    
    $InvokeSplat = @{
        Uri = "https://dev.azure.com/$Organization/$Project/_apis/policy/configurations?api-version=7.1-preview.1"
        Method = 'POST'
        Body = $Body
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSBuildPolicy

#region New-ADOPSElasticpool

function New-ADOPSElasticPool {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$PoolName,
        
        [Parameter(Mandatory)]
        $ElasticPoolObject,

        [Parameter()]
        [string]$ProjectId,

        [Parameter()]
        [switch]$AuthorizeAllPipelines,

        [Parameter()]
        [switch]$AutoProvisionProjectPools,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    } else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    if ($PSBoundParameters.ContainsKey('ProjectId')) {
        $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/elasticpools?poolName=$PoolName`&authorizeAllPipelines=$AuthorizeAllPipelines`&autoProvisionProjectPools=$AutoProvisionProjectPools`&projectId=$ProjectId`&api-version=7.1-preview.1"
    } else {
        $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/elasticpools?poolName=$PoolName`&authorizeAllPipelines=$AuthorizeAllPipelines`&autoProvisionProjectPools=$AutoProvisionProjectPools`&api-version=7.1-preview.1"
    }

    if ($ElasticPoolObject.gettype().name -eq 'String') {
        $Body = $ElasticPoolObject
    } else {
        try {
            $Body = $ElasticPoolObject | ConvertTo-Json -Depth 100
        }
        catch {
            throw "Unable to convert the content of the ElasticPoolObject to json."
        }
    }
    
    $Method = 'POST'
    $ElasticPoolInfo = InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization -Body $Body
    Write-Output $ElasticPoolInfo
}
#endregion New-ADOPSElasticpool

#region New-ADOPSElasticPoolObject

function New-ADOPSElasticPoolObject {
    [SkipTest('HasOrganizationParameter')]
    [CmdletBinding()]
    param (
        # Service Endpoint Id
        [Parameter(Mandatory)]
        [guid]
        $ServiceEndpointId,

        # Service Endpoint Scope
        [Parameter(Mandatory)]
        [guid]
        $ServiceEndpointScope,

        # Azure Id
        [Parameter(Mandatory)]
        [string]
        $AzureId,

        # Operating System Type
        [Parameter()]
        [ValidateSet('linux', 'windows')]
        [string]
        $OsType = 'linux',

        # MaxCapacity
        [Parameter()]
        [int]
        $MaxCapacity = 1,

        # DesiredIdle
        [Parameter()]
        [int]
        $DesiredIdle = 0,

        # Recycle VM after each use
        [Parameter()]
        [boolean]
        $RecycleAfterEachUse = $false,

        # Desired Size of pool
        [Parameter()]
        [int]
        $DesiredSize = 0,

        # Agent Interactive UI
        [Parameter()]
        [boolean]
        $AgentInteractiveUI = $false,

        # Time before scaling down
        [Parameter()]
        [int]
        $TimeToLiveMinues = 15,

        # maxSavedNodeCount
        [Parameter()]
        [int]
        $MaxSavedNodeCount = 0,

        # Output Type
        [Parameter()]
        [ValidateSet('json','pscustomobject')]
        [string]
        $OutputType = 'pscustomobject'
    )

    if ($DesiredIdle -gt $MaxCapacity) {
        throw "The desired idle count cannot be larger than the max capacity."
    }

    $ElasticPoolObject = [PSCustomObject]@{
        serviceEndpointId = $ServiceEndpointId
        serviceEndpointScope = $ServiceEndpointScope
        azureId = $AzureId
        maxCapacity = $MaxCapacity
        desiredIdle = $DesiredIdle
        recycleAfterEachUse = $RecycleAfterEachUse
        maxSavedNodeCount = $MaxSavedNodeCount
        osType = $OsType
        desiredSize = $DesiredSize
        agentInteractiveUI = $AgentInteractiveUI
        timeToLiveMinutes = $TimeToLiveMinues
    }
    
    if ($OutputType -eq 'json') {
        $ElasticPoolObject = $ElasticPoolObject | ConvertTo-Json -Depth 100
    }

    Write-Output $ElasticPoolObject
}
#endregion New-ADOPSElasticPoolObject

#region New-ADOPSEnvironment

function New-ADOPSEnvironment {
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization,
        
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Project,
        
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,
        
        [Parameter()]
        [string]$Description,
        
        [Parameter()]
        [string]$AdminGroup,
        
        [Parameter()]
        [switch]$SkipAdmin
    )
     
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }


    $Uri = "https://dev.azure.com/$organization/$project/_apis/distributedtask/environments?api-version=7.1-preview.1"

    $Body = [Ordered]@{
        name = $Name
        description = $Description
    } | ConvertTo-Json -Compress

    $InvokeSplat = @{
        Uri = $Uri
        Method = 'Post'
        Body = $Body
    }

    Write-Verbose "Setting up environment"
    $Environment = InvokeADOPSRestMethod @InvokeSplat

    if ($PSBoundParameters.ContainsKey('SkipAdmin')) {
        Write-Verbose 'Skipped admin group'
    }
    else {
        $secUri = "https://dev.azure.com/$organization/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/$($Environment.project.id)_$($Environment.id)?api-version=7.1-preview.1"

        if ([string]::IsNullOrEmpty($AdminGroup)) {
            $AdmGroupPN = "[$organization]\Project Administrators"
        } 
        else {
            $AdmGroupPN = $AdminGroup
        }
        $ProjAdm = (Get-ADOPSGroup | Where-Object {$_.principalName -eq $AdmGroupPN}).originId

        $SecInvokeSplat = @{
            Uri = $secUri
            Method = 'Put'
            Body = "[{`"userId`":`"$ProjAdm`",`"roleName`":`"Administrator`"}]"
        }

        try {
            $SecResult = InvokeADOPSRestMethod @SecInvokeSplat
        }
        catch {
            Write-Error 'Failed to update environment security. The environment may still have been created.'
        }
    }

    Write-Output $Environment
}
#endregion New-ADOPSEnvironment

#region New-ADOPSGitBranch

function New-ADOPSGitBranch {
    param (
    [Parameter()]
    [ValidateNotNullOrEmpty()]
    [string]$Organization,

    [Parameter(Mandatory)]
    [ValidatePattern('^[a-z0-9]{8}\-[a-z0-9]{4}\-[a-z0-9]{4}\-[a-z0-9]{4}\-[a-z0-9]{12}$', ErrorMessage = 'RepositoryId must be in GUID format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)')]
    [string]$RepositoryId,

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

    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$BranchName,

    [Parameter(Mandatory)]
    [ValidateLength(40,40)]
    [string]$CommitId
    )
    
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Body = @(
        [ordered]@{
            name = "refs/heads/$BranchName"
            oldObjectId = '0000000000000000000000000000000000000000'
            newObjectId = $CommitId
        }
    )
    $Body = ConvertTo-Json -InputObject $Body -Compress

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/git/repositories/$RepositoryId/refs?api-version=7.1-preview.1"
    $InvokeSplat = @{
        Uri = $Uri
        Method = 'Post'
        Body = $Body
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSGitBranch

#region New-ADOPSMergePolicy

function New-ADOPSMergePolicy {
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Project,

        [Parameter()]
        [string]$Organization,

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

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Branch,

        [Parameter()]
        [Switch]$allowNoFastForward,

        [Parameter()]
        [Switch]$allowSquash,

        [Parameter()]
        [Switch]$allowRebase,

        [Parameter()]
        [Switch]$allowRebaseMerge
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    if (-Not ($Branch -match '^\w+/\w+/\w+$')) {
        $Branch = "refs/heads/$Branch"
    }
    $GitBranchRef = $Branch

    $settings = [ordered]@{
        scope = @(
            [ordered]@{
                repositoryId = $RepositoryId
                refName = $GitBranchRef
                matchKind = "exact"
            }
        )
        allowNoFastForward = $allowNoFastForward.IsPresent
        allowSquash = $allowSquash.IsPresent
        allowRebase = $allowRebase.IsPresent
        allowRebaseMerge = $allowRebaseMerge.IsPresent
    }


    $Body = [ordered]@{
        type = [ordered]@{
            id = "fa4e907d-c16b-4a4c-9dfa-4916e5d171ab" 
        }
        isBlocking = $true
        isEnabled = $true
        settings = $settings
    } 
    
    $Body = $Body | ConvertTo-Json -Depth 10 -Compress
    
    $InvokeSplat = @{
        Uri = "https://dev.azure.com/$Organization/$Project/_apis/policy/configurations?api-version=7.1-preview.1"
        Method = 'POST'
        Body = $Body
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSMergePolicy

#region New-ADOPSPipeline

function New-ADOPSPipeline {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

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

        [Parameter(Mandatory)]
        [ValidateScript( { 
            $_ -like '*.yaml' -or
            $_ -like '*.yml'
        },
        ErrorMessage = "Path must be to a yaml file in your repository like: folder/file.yaml or folder/file.yml")] 
        [string]$YamlPath,

        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Repository,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$FolderPath,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/pipelines?api-version=7.1-preview.1"

    try {
        $RepositoryID = (Get-ADOPSRepository -Organization $Organization -Project $Project -Repository $Repository -ErrorAction Stop).id
    }
    catch {
        throw "The specified Repository $Repository was not found."
    }

    $Body = [ordered]@{
        "name" = $Name
        "folder" = "\$FolderPath"
        "configuration" = [ordered]@{
            "type" = "yaml"
            "path" = $YamlPath
            "repository" = [ordered]@{
                "id" = $RepositoryID
                "type" = "azureReposGit"
            }
        }
    }
    $Body = $Body | ConvertTo-Json -Compress

    $InvokeSplat = @{
        Method       = 'Post'
        Uri          = $URI
        Organization = $Organization
        Body         = $Body 
    }

    InvokeADOPSRestMethod @InvokeSplat

}
#endregion New-ADOPSPipeline

#region New-ADOPSProject

function New-ADOPSProject {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Description,
        
        [Parameter(Mandatory)]
        [ValidateSet('Private', 'Public')]
        [string]$Visibility,
        
        [Parameter()]
        [ValidateSet('Git', 'Tfvc')]
        [string]$SourceControlType = 'Git',
        
        # The process type for the project, such as Basic, Agile, Scrum or CMMI
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$ProcessTypeName,
        
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization,
        
        [Parameter()]
        [switch]$Wait
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    # Get organization process templates
    $URI = "https://dev.azure.com/$Organization/_apis/process/processes?api-version=7.1-preview.1"

    $InvokeSplat = @{
        Method       = 'Get'
        Uri          = $URI
        Organization = $Organization
    }

    $ProcessTemplates = (InvokeADOPSRestMethod @InvokeSplat).value

    if ([string]::IsNullOrWhiteSpace($ProcessTypeName)) {
        $ProcessTemplateTypeId = $ProcessTemplates | Where-Object isDefault -eq $true | Select-Object -ExpandProperty id
    }
    else {
        $ProcessTemplateTypeId = $ProcessTemplates | Where-Object name -eq $ProcessTypeName | Select-Object -ExpandProperty id
        if ([string]::IsNullOrWhiteSpace($ProcessTemplateTypeId)) {
            throw "The specified ProcessTypeName was not found amongst options: $($ProcessTemplates.name -join ', ')!"
        }
    }

    # Create project endpoint
    $URI = "https://dev.azure.com/$Organization/_apis/projects?api-version=7.1-preview.4"

    $Body = [ordered]@{
        'name'         = $Name
        'visibility'   = $Visibility
        'capabilities' = [ordered]@{
            'versioncontrol'  = [ordered]@{
                'sourceControlType' = $SourceControlType
            }
            'processTemplate' = [ordered]@{
                'templateTypeId' = $ProcessTemplateTypeId
            }
        }
    }
    if (-not [string]::IsNullOrEmpty($Description)) {
        $Body.Add('description', $Description)
    }
    $Body = $Body | ConvertTo-Json -Compress
    
    $InvokeSplat = @{
        Method       = 'Post'
        Uri          = $URI
        Body         = $Body
        Organization = $Organization
    }

    $Out = InvokeADOPSRestMethod @InvokeSplat

    if ($PSBoundParameters.ContainsKey('Wait')) {
        $projectCreated = $Out.status
        while ($projectCreated -ne 'succeeded') {
            $projectCreated = (Invoke-ADOPSRestMethod -Uri $Out.url -Method Get).status
            Start-Sleep -Seconds 1
        }
        $Out = Get-ADOPSProject -Project $Name 
    }

    $Out
}
#endregion New-ADOPSProject

#region New-ADOPSRepository

function New-ADOPSRepository {
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$Name,

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

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $ProjectID = (Get-ADOPSProject -Project $Project).id

    $URI = "https://dev.azure.com/$Organization/_apis/git/repositories?api-version=7.1-preview.1"
    $Body = "{""name"":""$Name"",""project"":{""id"":""$ProjectID""}}"

    $InvokeSplat = @{
        Uri           = $URI
        Method        = 'Post'
        Body          = $Body
        Organization  = $Organization
      }
    
      InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSRepository

#region New-ADOPSServiceConnection

function New-ADOPSServiceConnection {
    [cmdletbinding(DefaultParameterSetName = 'ServicePrincipal')]
    param(
        [Parameter()]
        [string]$Organization,
        
        [Parameter(Mandatory)]
        [string]$TenantId,

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

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

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

        [Parameter()]
        [string]$ConnectionName,
      
        [Parameter(Mandatory, ParameterSetName = 'ServicePrincipal')]
        [pscredential]$ServicePrincipal,

        [Parameter(Mandatory, ParameterSetName = 'ManagedServiceIdentity')]
        [switch]$ManagedIdentity
    )

    # Set organization
    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    # Get ProjectId
    $ProjectInfo = Get-ADOPSProject -Organization $Organization -Project $Project

    # Set connection name if not set by parameter
    if (-not $ConnectionName) {
        $ConnectionName = $SubscriptionName -replace " "
    }
    
    switch ($PSCmdlet.ParameterSetName) {
        
        'ServicePrincipal' {
            $authorization = [ordered]@{
                parameters = [ordered]@{
                    tenantid            = $TenantId
                    serviceprincipalid  = $ServicePrincipal.UserName
                    authenticationType  = "spnKey"
                    serviceprincipalkey = $ServicePrincipal.GetNetworkCredential().Password
                }
                scheme     = "ServicePrincipal"
            }
    
            $data = [ordered]@{
                subscriptionId   = $SubscriptionId
                subscriptionName = $SubscriptionName
                environment      = "AzureCloud"
                scopeLevel       = "Subscription"
                creationMode     = "Manual"
            }
        }

        'ManagedServiceIdentity' {
            $authorization = [ordered]@{
                parameters = [ordered]@{
                    tenantid = $TenantId
                }
                scheme     = "ManagedServiceIdentity"
            }
    
            $data = [ordered]@{
                subscriptionId   = $SubscriptionId
                subscriptionName = $SubscriptionName
                environment      = "AzureCloud"
                scopeLevel       = "Subscription"
            }
        }
    }

    # Create body for the API call
    $Body = [ordered]@{
        data                             = $data
        name                             = ($SubscriptionName -replace " ")
        type                             = "AzureRM"
        url                              = "https://management.azure.com/"
        authorization                    = $authorization
        isShared                         = $false
        isReady                          = $true
        serviceEndpointProjectReferences = @(
            [ordered]@{
                projectReference = [ordered]@{
                    id   = $ProjectInfo.Id
                    name = $Project
                }
                name             = $ConnectionName
            }
        )
    } | ConvertTo-Json -Depth 10

    # Run function
    $URI = "https://dev.azure.com/$Organization/$Project/_apis/serviceendpoint/endpoints?api-version=6.0-preview.4"
    $InvokeSplat = @{
        Uri          = $URI
        Method       = "POST"
        Body         = $Body
        Organization = $Organization
    }

    InvokeADOPSRestMethod @InvokeSplat

}
#endregion New-ADOPSServiceConnection

#region New-ADOPSUserStory

function New-ADOPSUserStory {
  [CmdletBinding()]
  param (
    [Parameter(Mandatory)]
    [ValidateNotNullOrEmpty()]
    [string]$Title,

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

    [Parameter()]
    [string]$Description,

    [Parameter()]
    [string]$Tags,

    [Parameter()]
    [string]$Priority,

    [Parameter()]
    [string]$Organization
  )

  if (-not [string]::IsNullOrEmpty($Organization)) {
    $Org = GetADOPSHeader -Organization $Organization
  }
  else {
    $Org = GetADOPSHeader
    $Organization = $Org['Organization']
  }


  $URI = "https://dev.azure.com/$Organization/$ProjectName/_apis/wit/workitems/`$User Story?api-version=5.1"
  $Method = 'POST'

  $desc = $Description.Replace('"', "'")
  $Body = "[
      {
        `"op`": `"add`",
        `"path`": `"/fields/System.Title`",
        `"value`": `"$($Title)`"
      },
      {
        `"op`": `"add`",
        `"path`": `"/fields/System.Description`",
        `"value`": `"$($desc)`"
      },
      {
        `"op`": `"add`",
        `"path`": `"/fields/System.Tags`",
        `"value`": `"$($Tags)`"
      },
      {
        `"op`": `"add`",
        `"path`": `"/fields/Microsoft.VSTS.Common.Priority`",
        `"value`": `"$($Priority)`"
      },
    ]"

    
  $ContentType= "application/json-patch+json"  
  
  $InvokeSplat = @{
    Uri           = $URI
    ContentType   = $ContentType
    Method        = $Method
    Body          = $Body
    Organization  = $Organization
  }

  InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSUserStory

#region New-ADOPSVariableGroup

function New-ADOPSVariableGroup {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$VariableGroupName,

        [Parameter(Mandatory, ParameterSetName = 'VariableSingle')]
        [string]$VariableName,

        [Parameter(Mandatory, ParameterSetName = 'VariableSingle')]
        [string]$VariableValue,

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

        [Parameter(ParameterSetName = 'VariableSingle')]
        [switch]$IsSecret,

        [Parameter(Mandatory, ParameterSetName = 'VariableHashtable')]
        [ValidateScript(
            {
                $_ | ForEach-Object { $_.Keys -Contains 'Name' -and $_.Keys -Contains 'IsSecret' -and $_.Keys -Contains 'Value' -and $_.Keys.count -eq 3 }
            },
            ErrorMessage = 'The hashtable must contain the following keys: Name, IsSecret, Value')]
        [hashtable[]]$VariableHashtable,

        [Parameter()]
        [string]$Description,

        [Parameter()]
        [string]$Organization
    )

    if ([string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }
    else {
        $Org = GetADOPSHeader -Organization $Organization
    }

    $ProjectInfo = Get-ADOPSProject -Organization $Organization -Project $Project

    $URI = "https://dev.azure.com/${Organization}/_apis/distributedtask/variablegroups?api-version=7.1-preview.2"
    $method = 'POST'

    if ($VariableName) {
        $Body = @{
            Name                           = $VariableGroupName
            Description                    = $Description
            Type                           = 'Vsts'
            variableGroupProjectReferences = @(@{
                    Name             = $VariableGroupName
                    Description      = $Description
                    projectReference = @{
                        Id = $ProjectInfo.Id
                    }
                })
            variables                      = @{
                $VariableName = @{
                    isSecret = $IsSecret.IsPresent
                    value    = $VariableValue
                }
            }
        } | ConvertTo-Json -Depth 10
    }
    else {

        $Variables = @{}
        foreach ($Hashtable in $VariableHashtable) {
            $Variables.Add(
                $Hashtable.Name, @{
                    isSecret = $Hashtable.IsSecret
                    value    = $Hashtable.Value
                }
            )
        }

        $Body = @{
            Name                           = $VariableGroupName
            Description                    = $Description
            Type                           = 'Vsts'
            variableGroupProjectReferences = @(@{
                    Name             = $VariableGroupName
                    Description      = $Description
                    projectReference = @{
                        Id = $($ProjectInfo.Id)
                    }
                })
            variables                      = $Variables
        } | ConvertTo-Json -Depth 10
    }

    InvokeADOPSRestMethod -Uri $Uri -Method $Method -Body $Body -Organization $Organization
}
#endregion New-ADOPSVariableGroup

#region New-ADOPSWiki

function New-ADOPSWiki {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$WikiName,
        
        [Parameter(Mandatory)]
        [string]$WikiRepository,

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

        [Parameter()]
        [string]$WikiRepositoryPath = '/',
        
        [Parameter()]
        [string]$GitBranch = 'main',

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $ProjectId = (Get-ADOPSProject -Project $Project).id
    $RepositoryId = (Get-ADOPSRepository -Project $Project -Repository $WikiRepository).id

    $URI = "https://dev.azure.com/$Organization/_apis/wiki/wikis?api-version=7.1-preview.2"
    
    $Method = 'Post'
    $Body = [ordered]@{
        'type' = 'codeWiki'
        'name' = $WikiName
        'projectId' = $ProjectId
        'repositoryId' = $RepositoryId
        'mappedPath' = $WikiRepositoryPath
        'version' = @{'version' = $GitBranch}
    } 

    $InvokeSplat = @{
        Uri = $URI
        Method = $Method
        Body = $Body | ConvertTo-Json -Compress
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion New-ADOPSWiki

#region Remove-ADOPSRepository

function Remove-ADOPSRepository {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory)]
        [string]$RepositoryID,

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

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $OrgInfo = GetADOPSHeader -Organization $Organization
    }
    else {
        $OrgInfo = GetADOPSHeader
        $Organization = $OrgInfo['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/git/repositories/$RepositoryID`?api-version=7.1-preview.1"
    
    $result = InvokeADOPSRestMethod -Uri $Uri -Method Delete -Organization $Organization

    if ($result.psobject.properties.name -contains 'value') {
        Write-Output -InputObject $result.value
    }
    else {
        Write-Output -InputObject $result
    }
}
#endregion Remove-ADOPSRepository

#region Remove-ADOPSVariableGroup

function Remove-ADOPSVariableGroup {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$VariableGroupName,

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

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/distributedtask/variablegroups?api-version=7.1-preview.2"
    $VariableGroups = (InvokeADOPSRestMethod -Uri $Uri -Method 'Get' -Organization $Organization).value

    $GroupToRemove = $VariableGroups | Where-Object name -eq $VariableGroupName
    if ($null -eq $GroupToRemove) {
        throw "Could not find group $VariableGroupName! Groups found: $($VariableGroups.name -join ', ')."
    }
    
    $ProjectId = (Get-ADOPSProject -Organization $Organization -Project $Project).id

    $URI = "https://dev.azure.com/$Organization/_apis/distributedtask/variablegroups/$($GroupToRemove.id)?projectIds=$ProjectId&api-version=7.1-preview.2"
    $null = InvokeADOPSRestMethod -Uri $Uri -Method 'Delete' -Organization $Organization
}
#endregion Remove-ADOPSVariableGroup

#region Save-ADOPSPipelineTask

function Save-ADOPSPipelineTask {
    [CmdletBinding(DefaultParameterSetName = 'InputData')]
    param (
        [Parameter(ParameterSetName = 'InputData')]
        [Parameter(ParameterSetName = 'InputObject')]
        [string]$Organization,

        [Parameter(ParameterSetName = 'InputData')]
        [Parameter(ParameterSetName = 'InputObject')]
        [string]$Path = ".",

        [Parameter(Mandatory, ParameterSetName = 'InputData')]
        [string]$TaskId,

        [Parameter(Mandatory, ParameterSetName = 'InputData')]
        [version]$TaskVersion,

        [Parameter(ParameterSetName = 'InputData')]
        [string]$FileName,

        [Parameter(Mandatory, ParameterSetName = 'InputObject', ValueFromPipeline, Position = 0)]
        [psobject[]]$InputObject
    )
    begin {}
    process {
        if (-not [string]::IsNullOrEmpty($Organization)) {
            $Org = GetADOPSHeader -Organization $Organization
        }
        else {
            $Org = GetADOPSHeader
            $Organization = $Org['Organization']
        }

        switch ($PSCmdlet.ParameterSetName) {
            'InputData' {
                if ([string]::IsNullOrEmpty($FileName)) {
                    $FileName = "$TaskId.$($TaskVersion.ToString(3)).zip"
                }
                if (-Not $FileName -match '.zip$' ) {
                    $FileName = "$FileName.zip"
                }

                [array]$FilesToDownload = @{
                    TaskId = $TaskId
                    TaskVersionString = $TaskVersion.ToString(3)
                    OutputFile = Join-Path -Path $Path -ChildPath $FileName
                }
            }
            'InputObject' {
                [array]$FilesToDownload = foreach ($o in $InputObject) {
                    @{
                        TaskId = $o.id
                        TaskVersionString = "$($o.version.major).$($o.version.minor).$($o.version.patch)"
                        OutputFile = Join-Path -Path $Path -ChildPath "$($o.name)-$($o.id)-$($o.version.major).$($o.version.minor).$($o.version.patch).zip"
                    }
                }
            }
        }

        foreach ($File in $FilesToDownload) {
            $Url = "https://dev.azure.com/$Organization/_apis/distributedtask/tasks/$($File.TaskId)/$($File.TaskversionString)"
            InvokeADOPSRestMethod -Uri $Url -Method Get -OutFile $File.OutputFile
        }
    }
    end {}
}
#endregion Save-ADOPSPipelineTask

#region Set-ADOPSElasticPool

function Set-ADOPSElasticPool {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [int]$PoolId,
        
        [Parameter(Mandatory)]
        $ElasticPoolObject,

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/_apis/distributedtask/elasticpools/$PoolId`?api-version=7.1-preview.1"

    if ($ElasticPoolObject.GetType().Name -eq 'String') {
        $Body = $ElasticPoolObject
    }
    else {
        try {
            $Body = $ElasticPoolObject | ConvertTo-Json -Depth 100
        }
        catch {
            throw "Unable to convert the content of the ElasticPoolObject to json."
        }
    }
    
    $Method = 'PATCH'
    $ElasticPoolInfo = InvokeADOPSRestMethod -Uri $Uri -Method $Method -Organization $Organization -Body $Body
    Write-Output $ElasticPoolInfo
}
#endregion Set-ADOPSElasticPool

#region Set-ADOPSGitPermission

function Set-ADOPSGitPermission {
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization,
        
        [Parameter(Mandatory)]
        [ValidatePAttern('^[a-z0-9]{8}\-[a-z0-9]{4}\-[a-z0-9]{4}\-[a-z0-9]{4}\-[a-z0-9]{12}$', ErrorMessage = 'ProjectId must be in GUID format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)')]
        [string]$ProjectId,
        
        [Parameter(Mandatory)]
        [ValidatePAttern('^[a-z0-9]{8}\-[a-z0-9]{4}\-[a-z0-9]{4}\-[a-z0-9]{4}\-[a-z0-9]{12}$', ErrorMessage = 'ProjectId must be in GUID format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)')]
        [string]$RepositoryId,
        
        [Parameter(Mandatory)]
        [ValidatePattern('^[a-z]{3,5}\.[a-zA-Z0-9]{40,}$', ErrorMessage = 'Descriptor must be in the descriptor format')]
        [string]$Descriptor,
        
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [AccessLevels[]]$Allow,
        
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [AccessLevels[]]$Deny
    )
    
    if (-not $Allow -and -not $Deny) {
        Write-Verbose 'No allow or deny rules set'
    }
    else {
        if ($null -eq $Allow) {
            $allowRules = 0
        }
        else {
            $allowRules = ([accesslevels]$Allow).value__
        }
        if ($null -eq $Deny) {
            $denyRules = 0
        }
        else {
            $denyRules = ([accesslevels]$Deny).value__
        }
    
        if (-not [string]::IsNullOrEmpty($Organization)) {
            $Org = GetADOPSHeader -Organization $Organization
        }
        else {
            $Org = GetADOPSHeader
            $Organization = $Org['Organization']
        }
        
        $SubjectDescriptor = (InvokeADOPSRestMethod -Uri "https://vssps.dev.azure.com/$Organization/_apis/identities?subjectDescriptors=$Descriptor&queryMembership=None&api-version=7.1-preview.1" -Method Get).value.descriptor

        $Body = [ordered]@{
            token                = "repov2/$Projectid/$RepositoryId"
            merge                = $true
            accessControlEntries = @(
                [ordered]@{
                    allow      = $allowRules
                    deny       = $denyRules
                    descriptor = $SubjectDescriptor
                }
            )
        } | ConvertTo-Json -Compress -Depth 10
        
        $Uri = "https://dev.azure.com/$Organization/_apis/accesscontrolentries/2e9eb7ed-3c0a-47d4-87c1-0ffdd275fd87?api-version=7.1-preview.1"
        
        $InvokeSplat = @{
            Uri = $Uri 
            Method = 'Post' 
            Body = $Body
        }
        
        InvokeADOPSRestMethod @InvokeSplat
    }
}
#endregion Set-ADOPSGitPermission

#region Set-ADOPSRepository

function Set-ADOPSRepository {
    param (
        [Parameter(Mandatory)]
        [ValidateNotNullOrEmpty()]
        [string]$RepositoryId,

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

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$Organization,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$DefaultBranch,

        [Parameter()]
        [bool]$IsDisabled,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$NewName
    )

    if ( ([string]::IsNullOrEmpty($DefaultBranch)) -and ([string]::IsNullOrEmpty($NewName)) -and (-Not $PSBoundParameters.ContainsKey('IsDisabled')) ) {
        # Nothing to do, exit early
    }
    else {
        if (-not [string]::IsNullOrEmpty($Organization)) {
            $Org = GetADOPSHeader -Organization $Organization
        }
        else {
            $Org = GetADOPSHeader
            $Organization = $Org['Organization']
        }

        $URI = "https://dev.azure.com/${Organization}/${Project}/_apis/git/repositories/${RepositoryId}?api-version=7.1-preview.1"

        $Body = [ordered]@{}

        if (-Not [string]::IsNullOrEmpty($NewName)) {
            $Body.Add('name',$NewName)
        }

        if (-Not [string]::IsNullOrEmpty($DefaultBranch)) {
            if (-Not ($DefaultBranch -match '^\w+/\w+/\w+$')) {
                $DefaultBranch = "refs/heads/$DefaultBranch"
            }
            $Body.Add('defaultBranch',$DefaultBranch)
        }

        if ($PSBoundParameters.ContainsKey('IsDisabled')) {
            $Body.Add('isDisabled',$IsDisabled)
        }

        $InvokeSplat = @{
            URI = $Uri
            Method = 'Patch'
            Body = $Body | ConvertTo-Json -Compress
        }

        InvokeADOPSRestMethod @InvokeSplat
    }
}
#endregion Set-ADOPSRepository

#region Set-ADOPSServiceConnection

function Set-ADOPSServiceConnection {
    [CmdletBinding(DefaultParameterSetName = 'ServicePrincipal')]
    param (
        [Parameter()]
        [string]$Organization,
        
        [Parameter(Mandatory)]
        [string]$TenantId,

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

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

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

        [Parameter(Mandatory)]
        [guid]$ServiceEndpointId,

        [Parameter()]
        [string]$ConnectionName,

        [Parameter()]
        [string]$Description,
        
        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [string]$EndpointOperation,
      
        [Parameter(Mandatory, ParameterSetName = 'ServicePrincipal')]
        [pscredential]$ServicePrincipal,

        [Parameter(Mandatory, ParameterSetName = 'ManagedServiceIdentity')]
        [switch]$ManagedIdentity
    )
    
    process {

        # Set organization
        if (-not [string]::IsNullOrEmpty($Organization)) {
            $Org = GetADOPSHeader -Organization $Organization
        }
        else {
            $Org = GetADOPSHeader
            $Organization = $Org['Organization']
        }

        # Get ProjectId
        $ProjectInfo = Get-ADOPSProject -Organization $Organization -Project $Project

        # Set connection name if not set by parameter
        if (-not $ConnectionName) {
            $ConnectionName = $SubscriptionName -replace " "
        }

        switch ($PSCmdlet.ParameterSetName) {
        
            'ServicePrincipal' {
                $authorization = [ordered]@{
                    parameters = [ordered]@{
                        tenantid            = $TenantId
                        serviceprincipalid  = $ServicePrincipal.UserName
                        authenticationType  = "spnKey"
                        serviceprincipalkey = $ServicePrincipal.GetNetworkCredential().Password
                    }
                    scheme     = "ServicePrincipal"
                }
        
                $data = [ordered]@{
                    subscriptionId   = $SubscriptionId
                    subscriptionName = $SubscriptionName
                    environment      = "AzureCloud"
                    scopeLevel       = "Subscription"
                    creationMode     = "Manual"
                }
            }
    
            'ManagedServiceIdentity' {
                $authorization = [ordered]@{
                    parameters = [ordered]@{
                        tenantid = $TenantId
                    }
                    scheme     = "ManagedServiceIdentity"
                }
            }
        }

        # Create body for the API call
        $Body = [ordered]@{
            authorization                    = $authorization
            data                             = $data
            description                      = "$Description"
            id                               = $ServiceConnectionId
            isReady                          = $true
            isShared                         = $false
            name                             = ($SubscriptionName -replace " ")
            serviceEndpointProjectReferences = @(
                [ordered]@{
                    projectReference = [ordered]@{
                        id   = $ProjectInfo.Id
                        name = $Project
                    }
                    name             = $ConnectionName
                }
            )
            type                             = "AzureRM"
            url                              = "https://management.azure.com/"
        } | ConvertTo-Json -Depth 10
    
        if ($PSBoundParameters.ContainsKey('EndpointOperation')) {
            $URI = "https://dev.azure.com/$Organization/_apis/serviceendpoint/endpoints/$ServiceEndpointId`?operation=$EndpointOperation`&api-version=7.1-preview.4"
        }
        else {
            $URI = "https://dev.azure.com/$Organization/_apis/serviceendpoint/endpoints/$ServiceEndpointId`?api-version=7.1-preview.4"
        }
        
        $InvokeSplat = @{
            Uri          = $URI
            Method       = "PUT"
            Body         = $Body
            Organization = $Organization
        }
    
        InvokeADOPSRestMethod @InvokeSplat

    }
}
#endregion Set-ADOPSServiceConnection

#region Start-ADOPSPipeline

function Start-ADOPSPipeline {
    param (
        [Parameter(Mandatory)]
        [string]$Name,

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

        [Parameter()]
        [string]$Branch = 'main',

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
    }

    $AllPipelinesURI = "https://dev.azure.com/$($Org['Organization'])/$Project/_apis/pipelines?api-version=7.1-preview.1"
    $AllPipelines = InvokeADOPSRestMethod -Method Get -Uri $AllPipelinesURI -Organization $Org['Organization']
    $PipelineID = ($AllPipelines.value | Where-Object -Property Name -EQ $Name).id

    if ([string]::IsNullOrEmpty($PipelineID)) {
        throw "No pipeline with name $Name found."
    }

    $URI = "https://dev.azure.com/$($Org['Organization'])/$Project/_apis/pipelines/$PipelineID/runs?api-version=7.1-preview.1"
    $Body = '{"stagesToSkip":[],"resources":{"repositories":{"self":{"refName":"refs/heads/' + $Branch + '"}}},"variables":{}}'
    
    $InvokeSplat = @{
        Method = 'Post' 
        Uri = $URI 
        Body = $Body
        Organization = $Org['Organization']
    }

    InvokeADOPSRestMethod @InvokeSplat
}
#endregion Start-ADOPSPipeline

#region Test-ADOPSYamlFile

function Test-ADOPSYamlFile {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory)]
        [string]$Project,

        [Parameter(Mandatory)]
        [ValidateScript({
            $_ -match '.*\.y[aA]{0,1}ml$'
        }, ErrorMessage = 'Fileextension must be ".yaml" or ".yml"')]
        [string]$File,

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

        [Parameter()]
        [string]$Organization
    )

    if (-not [string]::IsNullOrEmpty($Organization)) {
        $Org = GetADOPSHeader -Organization $Organization
    }
    else {
        $Org = GetADOPSHeader
        $Organization = $Org['Organization']
    }

    $Uri = "https://dev.azure.com/$Organization/$Project/_apis/pipelines/$PipelineId/runs?api-version=7.1-preview.1"

    $FileData = Get-Content $File -Raw

    $Body = @{
        previewRun = $true
        templateParameters = @{}
        resources = @{}
        yamlOverride = $FileData
    } | ConvertTo-Json -Depth 10 -Compress
    
    $InvokeSplat = @{
        Uri           = $URI
        Method        = 'Post'
        Body          = $Body
        Organization  = $Organization
      }
    
    try {
        $Result = InvokeADOPSRestMethod @InvokeSplat
        Write-Output "$file validation success."
    } 
    catch [Microsoft.PowerShell.Commands.HttpResponseException] {
        if ($_.ErrorDetails.Message) {
            $r = $_.ErrorDetails.Message | ConvertFrom-Json
            if ($r.typeName -like '*PipelineValidationException*') {
                Write-Warning "Validation failed:`n$($r.message)"
            }
            else {
                throw $_
            }
        }
    }
}
#endregion Test-ADOPSYamlFile