Private/New-PSGalleryYamlFile.ps1
function New-PSGalleryYamlFile { <# .SYNOPSIS Creates a YAML file for an Azure DevOps pipeline to publish a PowerShell module to the PowerShell Gallery. .DESCRIPTION This function automates the creation of a YAML file suitable for configuring a PowerShell Gallery publishing pipeline within Azure DevOps. The generated YAML includes trigger, pool, and task definitions to handle module publishing. .PARAMETER Path Required. Specifies the absolute path where the YAML file will be created. .PARAMETER Name Required. The name of the PowerShell module. .PARAMETER DevOpsPath Required. The relative path to the module folder within the DevOps repository. .EXAMPLE New-PSGalleryYamlFile -Path C:\MyProject\CI -Name MyModule -RelativePath Modules This creates a file named "MyModule_PSGallery_Pipeline.yaml" in the "C:\MyProject\CI" directory. .NOTES Author: owen.heaume Version: 1.0.0 - Initial release 1.0.1 - Change 'DevopsPath' to 'RelativePath' #> 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: $_" } # Here-string for YAML content (indentation is essential) $yamlContent = @" trigger: paths: include: - "`$(Build.SourcesDirectory)/$($RelativePath.replace('\', '/'))/$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)/$($RelativePath.replace('\', '/'))/$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 occured 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: $_" } } |