Private/New-YamlFile.ps1
function New-YamlFile { <# .SYNOPSIS Creates a YAML file for an Azure DevOps pipeline with Pester tests integration. .DESCRIPTION This function creates a YAML file with a basic Azure DevOps pipeline structure. The pipeline includes steps to run Pester tests, publish code coverage results, and potentially fail the build if tests don't pass. .PARAMETER Path Required. The path to the folder where the YAML file should be created. .PARAMETER Name Required. The name of the function (this will be used in the filename). .PARAMETER DevOpsPath Required. The DevOps path to the function (used for proper Pester path configuration). .EXAMPLE New-YamlFile -Path "C:\ohtemp15\My-Function" -Name "My-Function" -DevOpsPath "_GBL\Scripts" Creates a YAML file named "My-Function_Pester_Pipeline.yaml" .NOTES Author: owen.heaume Version: 1.0.0 - Initial release #> 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)_Pester_Pipeline.yaml" -ea Stop } catch { throw "Error joining path: $_" } # Here-string for YAML content (indentation is essential) $yamlContent = @" trigger: branches: include: - main paths: include: - $($RelativePath.replace('\', '/'))/$Name/src/* pool: vmImage: 'windows-latest' steps: - powershell: | # Path to the Pester configuration file `$pesterConfigFile = '`$(System.DefaultWorkingDirectory)/$($RelativePath.replace('\', '/'))/$Name/test.ps1' # Check if configuration file exists if (Test-Path `$pesterConfigFile) { # Install Pester (if necessary) if (-not (Get-Module -ListAvailable -Name Pester)) { Install-Module -Name Pester -Force -Scope CurrentUser } # Run Pester tests `$testResults = Invoke-Pester -Path `$pesterConfigFile -output detailed # Fail build if any tests fail if (`$testResults.FailedCount -gt 0) { Write-Host "Tests failed! Failing the build." exit 1 } else { Write-Host "All Pester tests passed!" } } else { Write-Host "Pester configuration file not found." } displayName: 'Run Pester Tests' - task: PublishCodeCoverageResults@1 displayName: 'Publish Code Coverage Results' inputs: codeCoverageTool: 'JaCoCo' summaryFileLocation: '`$(System.DefaultWorkingDirectory)/$($RelativePath.replace('\', '/'))/$Name/coverage.xml' pathToSources: '`$(System.DefaultWorkingDirectory)/$($RelativePath.replace('\', '/'))/$Name/src' "@ # 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: $_" } } |