Private/New-PSGalleryYamlFile.ps1

function New-PSGalleryYamlFile {
    Param(
        [Parameter(Mandatory)]
        [string] $Path,

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

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

    # Construct the full file path
    try {
        $yamlFilePath = Join-Path -Path "$Path\$name" -ChildPath "$($Name)_PSGallery_Pipeline.yaml" -ea Stop
    } catch {
        throw "Error joining path: $_"
    }

    # Replace backslashes in $RelativePath
    $formattedRelativePath = $RelativePath -replace '\\', '/'

    # Here-string for YAML content (indentation is essential)
    $yamlContent = @"
trigger:
    paths:
        include:
        - "$formattedRelativePath/$name/$name/$name.psd1"
 
pool:
    vmImage: 'windows-latest'
 
steps:
- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
        # Import the PowerShellGet module
        Import-Module PowerShellGet -Force
 
        # Set the PowerShell Gallery API key from the variable
        \$ApiKey = "\$(PSGAL_API_KEY)"
 
        # Set the relative path to the module folder within the repository
        \$ModuleFolder = "\$(Build.SourcesDirectory)/$formattedRelativePath/$name/$name"
 
        # Publish the module to the gallery
        write-host "Publishing module..." -ForegroundColor DarkGreen
        try {
            Publish-Module -Path \$ModuleFolder -NuGetApiKey \$ApiKey -ea stop -ev x
        } catch {
            write-warning "An error occurred publishing the module: \$x"
        }
"@


    # Create the YAML file
    try {
        Write-Host "Creating YAML file: $yamlFilePath" -ForegroundColor DarkCyan
        if (Test-Path $yamlFilePath) {
            Write-Host 'YAML file already exists' -ForegroundColor DarkYellow
        } else {
            $yamlContent | Out-File -FilePath $yamlFilePath -ea Stop
            Write-Host 'YAML file created successfully' -ForegroundColor DarkGreen
        }
    } catch {
        throw "Error writing YAML file: $_"
    }
}