TD.Util.psm1

<#
.SYNOPSIS
Get the Azure DevOps Personal Access Token from Azure Devops Hosted Agent (In build/deploy) or the Windows Credential Store
 
.DESCRIPTION
Get the Azure DevOps Personal Access Token from Azure Devops Hosted Agent (In build/deploy) or the Windows Credential Store. This function is MS Windows only when running local.
 
.PARAMETER Url
Url of the Azure DevOps subscription like https://(mycompany)@dev.azure.com/(mycompany)
 
.Example
$token = Get-AzureDevOpsAccessToken 'https://mycompany@dev.azure.com/mycompany')
#>

function Get-AzureDevOpsAccessToken($Url)
{
    $token = $env:SYSTEM_ACCESSTOKEN
    if ([string]::IsNullOrEmpty($token))
    {
        if (-not(Get-Module CredentialManager -ListAvailable)) { Install-Module CredentialManager -Scope CurrentUser -Force }
        Import-Module CredentialManager
        $credential = Get-StoredCredential -Target "git:$Url"
        if ($null -eq $credential)
        {
            Throw "No Azure DevOps credentials found in credential store"
        }
        Write-Verbose "Use Azure DevOps Access Token from Windows Credential Store"
        $token = $credential.GetNetworkCredential().Password
    }
    return $token
}
<#
.SYNOPSIS
Get the Azure DevOps Credentials from Azure Devops Hosted Agent (In build/deploy) or the Windows Credential Store
 
.DESCRIPTION
Get the Azure DevOps Credentials from Azure Devops Hosted Agent (In build/deploy) or the Windows Credential Store. This function is MS Windows only when running local.
 
.PARAMETER Url
Url of the Azure DevOps subscription like https://(mycompany)@dev.azure.com/(mycompany)
 
.Example
$cred = Get-AzureDevOpsCredential 'https://mycompany@dev.azure.com/mycompany')
#>

function Get-AzureDevOpsCredential($Url)
{
    $token = $env:SYSTEM_ACCESSTOKEN
    if ([string]::IsNullOrEmpty($token)) 
    {
        if (-not(Get-Module CredentialManager -ListAvailable)) { Install-Module CredentialManager -Scope CurrentUser -Force }
        Import-Module CredentialManager
        $credential = Get-StoredCredential -Target "git:$Url"
        if ($null -eq $credential)
        {
            Throw "No Azure DevOps credentials found. It should be passed in via env:SYSTEM_ACCESSTOKEN."
        }
        Write-Verbose "Use Azure DevOps Access Token from Windows Credential Store"
    }
    else
    {
        Write-Verbose "Use Azure DevOps Access Token from Hosted Agent"
        $secureToken = $token | ConvertTo-SecureString -AsPlainText -Force
        $credential = New-Object System.Management.Automation.PSCredential(".", $secureToken)
    }
    return $credential
}
<#
.SYNOPSIS
Import PowerShell module(s) and if not found install them from Azure DevOps Artifacts
 
.DESCRIPTION
Import PowerShell module(s) and if not found install them from Azure DevOps Artifacts
 
.PARAMETER PackageSource
Azure DevOps packagesource name
 
.PARAMETER Modules
Array of modules to import
 
.PARAMETER Credential
Credentials to access feed
 
.PARAMETER Latest
Always import latest modules
 
.EXAMPLE
Register-AzureDevOpsPackageSource -Name myFeed -Url https://pkgs.dev.azure.com/myCompany/_packaging/myFeed/nuget/v2
Import-AzureDevOpsModules -PackageSource 'myFeed' -Modules @('myModule') -Latest
#>

function Import-AzureDevOpsModules($PackageSource, $Modules, [System.Management.Automation.PSCredential]$Credential, [Switch]$Latest)
{
    foreach ($module in $Modules)
    {
        if (-not (Get-Module -ListAvailable -Name $module) -or $Latest.IsPresent)
        {
            Install-Module $module -Repository $PackageSource -Scope CurrentUser -Force -AllowClobber -Credential $Credential
        }
        else
        {
            Import-Module $module
        }
    }
}
<#
.SYNOPSIS
Publish the PowerShell Package to the Azure Devops Feed / Artifacts
 
.DESCRIPTION
Publish the PowerShell Package to the Azure Devops Feed / Artifacts. Depends on nuget.exe installed and in environment path.
 
Strategy:
- Register feed with nuget
- Register local temp feed to use Powershell Publish-Module command
- Publish locally created module to feed with nuget.exe
 
.PARAMETER ModuleName
Name of the PowerShell Module to publish
 
.PARAMETER ModulePath
Root path of the module
 
.PARAMETER Feedname
Name of the Azure DevOps feed
 
.PARAMETER FeedUrl
Url of the Azure DevOps feed
 
.PARAMETER AccessToken
Personal AccessToken used for Azure DevOps Feed push/publish
 
.Example
Publish-PackageToAzureDevOps -ModuleName 'MyModule' -ModulePath './Output' -Feedname 'MyFeed' -FeedUrl 'https://pkgs.dev.azure.com/mycompany/_packaging/MyFeed/nuget/v2' -AccessToken 'sasasasa'
 
#>

function Publish-PackageToAzureDevOps($ModuleName, $ModulePath = './Output', $Feedname, $FeedUrl, $AccessToken)
{
    $packageSource = $Feedname
    $packageFeedUrl = $FeedUrl

    $deployPath = Join-Path $ModulePath $ModuleName

    # register nuget feed
    $nuGet = (Get-Command 'nuget').Source
    &$nuGet sources Remove -Name $packageSource
    [string]$r = &$nuGet sources
    if (!($r.Contains($packageSource)))
    {
        # add as NuGet feed
        Write-Verbose "Add NuGet source"
        &$nuGet sources Add -Name $packageSource -Source $packageFeedUrl -username "." -password $AccessToken
    }

    # get module version
    $manifestFile = "./$ModuleName/$ModuleName.psd1"
    $manifest = Import-PowerShellDataFile -Path $manifestFile
    $version = $manifest.Item('ModuleVersion')
    if (!$version) { Throw "No module version found in $manifestFile" } else { Write-Host "$moduleName version: $version" }

    $tmpFeedPath = Join-Path ([System.IO.Path]::GetTempPath()) "$(New-Guid)-Localfeed"
    New-Item -Path $tmpFeedPath -ItemType Directory -ErrorAction Ignore -Force | Out-Null
    try 
    {
        # register temp feed for export package
        if (Get-PSRepository -Name LocalFeed -ErrorAction Ignore)
        {
            Unregister-PSRepository  -Name LocalFeed
        }
        Register-PSRepository -Name LocalFeed -SourceLocation $tmpFeedPath -PublishLocation $tmpFeedPath -InstallationPolicy Trusted

        # publish to temp feed
        $packageName = "$moduleName.$version.nupkg"
        $package = (Join-Path $tmpFeedPath $packageName)
        Write-Verbose "Publish Module $package"
        Publish-Module -Path $deployPath -Repository LocalFeed -Force -ErrorAction Ignore
        if (!(Test-Path $package))
        {
            Throw "Nuget package $package not created"
        }

        # publish package from tmp/local feed to PS feed
        Write-Verbose "Push package $packageName in $tmpFeedPath"
        Push-Location $tmpFeedPath
        try 
        {
            nuget push $packageName -source $packageSource -Apikey Az -NonInteractive
            if ($LastExitCode -ne 0)
            {
                Throw "Error pushing nuget package $packageName to feed $packageSource ($packageFeedUrl)"
            }
        }
        finally
        {
            Pop-Location    
        }
    }
    finally 
    {
        Remove-Item -Path $tmpFeedPath -Force -Recurse
    } 
}
<#
.SYNOPSIS
Registers a package source from AzureDevOps Feed / Artifacts
 
.DESCRIPTION
Registers a package source from AzureDevOps Feed /Artifacts. If already found removes reference first.
 
.PARAMETER Name
Name of package source
 
.PARAMETER Url
Url of package feed
 
.PARAMETER Credential
Credentials to access feed
 
.Example
Register-AzureDevOpsPackageSource -Name myFeed -Url https://pkgs.dev.azure.com/myCompany/_packaging/myFeed/nuget/v2
#>

function Register-AzureDevOpsPackageSource($Name, $Url, [System.Management.Automation.PSCredential]$Credential)
{
    if (Get-PSRepository -Name $Name -ErrorAction Ignore) { Unregister-PSRepository -Name $Name }
    Register-PSRepository -Name $Name -SourceLocation $Url -InstallationPolicy Trusted -Credential $Credential
}