PublishToGallery.ps1

[CmdletBinding(SupportsShouldProcess)]
param(
    [string] $NuGetApiKey,

    [string] $Repository = 'PSGallery',

    [string] $ManifestPath,

    [switch] $Force
)

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

if (-not $NuGetApiKey) {
    $fromVar = $null
    try { $fromVar = Get-Variable -Name 'NuGetApiKey' -Scope Global -ValueOnly -ErrorAction Stop } catch { }
    if (-not $fromVar) {
        try { $fromVar = Get-Variable -Name 'NuGetApiKey' -ValueOnly -ErrorAction Stop } catch { }
    }

    if ($fromVar) {
        $NuGetApiKey = $fromVar
    } elseif ($env:NUGET_API_KEY) {
        $NuGetApiKey = $env:NUGET_API_KEY
    }
}

if (-not $NuGetApiKey) {
    throw "NuGet API key not provided. Pass -NuGetApiKey or set `$NuGetApiKey or `$env:NUGET_API_KEY."
}

if (-not $ManifestPath) {
    $ManifestPath = Join-Path -Path $PSScriptRoot -ChildPath 'PSUnifiedAgents.psd1'
}

if (-not (Test-Path -LiteralPath $ManifestPath)) {
    throw "Manifest not found: $ManifestPath"
}

# Avoid hard-failing on Test-ModuleManifest under Windows PowerShell 5.1 when the manifest requires PowerShell 7.x.
$moduleName = (Get-Item -LiteralPath $ManifestPath).BaseName
try {
    $null = Test-ModuleManifest -Path $ManifestPath -ErrorAction Stop
} catch {
    Write-Verbose "Test-ModuleManifest failed for '$ManifestPath': $($_.Exception.Message)"
}

$publishParams = @{
    Path        = $PSScriptRoot
    NuGetApiKey = $NuGetApiKey
    Repository  = $Repository
    ErrorAction = 'Stop'
}

if ($Force) {
    $publishParams.Force = $true
}

if ($PSCmdlet.ShouldProcess($Repository, "Publish module '$moduleName' from '$PSScriptRoot'")) {
    Publish-Module @publishParams
}