Functions/PersonalAccessToken/Get-FpsAzDoPat.ps1

<#
.SYNOPSIS
    Returns a Azure DevOps PAT token.
    User interaction might be required when AzDoPatMethod CredentialManager is used.
.DESCRIPTION
    Method 'CredentialManager' retreives a stored PAT from the Windows Credential Manager with credential name $CredentialName.
    Method 'Az.Accounts' generates a new temporary (1h) PAT token through the Azure API with your current domain account.
.EXAMPLE
    Get-FpsAzDoPat -AzDoPatMethod 'CredentialManager' -CredentialName 'PowershellPATAzureDevOps'
.EXAMPLE
    Get-FpsAzDoPat -AzDoPatMethod 'Az.Accounts'
#>


function Get-FpsAzDoPat {

    param(
        [ValidateSet('Az.Accounts', 'CredentialManager')]
        [string] $AzDoPatMethod  = 'CredentialManager', 

        [string] $CredentialName = 'PowershellPATAzureDevOps'
    )

    # Get Azure DevOps Personal Access Token (PAT)
    switch ($AzDoPatMethod){
            
        # Requests a new temporary PAT, which is valid for 1 hour.
        'Az.Accounts' {
            # Import PowerShell module Az.Accounts, required obtain azure token
            Import-FpsModule -ModuleNames 'Az.Accounts'

            $azProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
            if(-not $azProfile.Accounts.Count) {
                Connect-AzAccount -ErrorAction Stop | Out-Null
            }
            $currentAzureContext = Get-AzContext
            $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azProfile)

            'Getting access token for tenant {0}' -f $currentAzureContext.Tenant.TenantId | Write-Host
            $azDoPat = $profileClient.AcquireAccessToken($currentAzureContext.Tenant.TenantId).AccessToken
        }
        
        # Read PAT from CredentialManager. If no valid PAT is pressent, ask user for new PAT.
        'CredentialManager'{
            # Import PowerShell module CredentialManager, required to read and store Azure DevOps PAT token
            Import-FpsModule -ModuleNames 'CredentialManager'

            # Get personal Access Token (PAT)
            $azDoPat = Get-StoredCredential -Target $CredentialName 

            # If there is no PAT with the credentialName stored locally
            if([string]::IsNullOrEmpty($azDoPat) -eq $true){
                'No Personal Access Token (PAT) with the name {0} is found.' -f $CredentialName | Write-Host
                Set-FpsAzDoPat -CredentialName $CredentialName
                $azDoPat = Get-StoredCredential -Target $CredentialName 
            }

            # Convert PAT
            $azDoPat = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($azDoPat.Password)
            $azDoPat = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($azDoPat)
            
            return  $azDoPat
        }
    }
}

Export-ModuleMember -Function Get-FpsAzDoPat