Private/New-PstProcessBlock.ps1
|
function New-PstProcessBlock { <# .SYNOPSIS Generates PowerShell process block code. .DESCRIPTION Creates a formatted process block with main logic placeholder and error handling based on complexity level. .PARAMETER FunctionName The name of the function (for debug/error messages). .PARAMETER Complexity The complexity level: Basic, Standard, or Advanced. .PARAMETER HasShouldProcess Whether to include ShouldProcess logic. .EXAMPLE New-PstProcessBlock -FunctionName "Set-UserData" -Complexity Standard -HasShouldProcess $true Generates a Standard complexity process block with ShouldProcess. .NOTES Version: 1.0 Author: numidia Creation Date: 2025-12-01 Purpose: Generate process blocks for functions #> [CmdletBinding()] [OutputType([string])] param( [Parameter(Mandatory = $true)] [string]$FunctionName, [Parameter(Mandatory = $true)] [ValidateSet('Basic', 'Standard', 'Advanced')] [string]$Complexity, [Parameter(Mandatory = $false)] [bool]$HasShouldProcess = $false ) begin { Write-Debug "Begin '$($MyInvocation.MyCommand.Name)' at '$(Get-Date)'" } process { try { $features = Get-PstComplexityFeatures -Complexity $Complexity -Type Function $sb = [System.Text.StringBuilder]::new() [void]$sb.AppendLine(' process {') [void]$sb.AppendLine(' try {') # Add ShouldProcess for Standard/Advanced if applicable if ($HasShouldProcess -and $features.CmdletBinding.SupportsShouldProcess) { [void]$sb.AppendLine(' if ($PSCmdlet.ShouldProcess(''Target'', ''Operation'')) {') [void]$sb.AppendLine(' # Main function logic here') [void]$sb.AppendLine(' }') } else { [void]$sb.AppendLine(' # Main function logic here') } # Error handling based on complexity [void]$sb.Append(' }') [void]$sb.AppendLine() if ($features.ErrorHandling.UseSpecificExceptions) { [void]$sb.AppendLine(' catch [System.IO.FileNotFoundException] {') [void]$sb.AppendLine(' Write-Error "File not found: $_"') [void]$sb.AppendLine(' }') } [void]$sb.AppendLine(' catch {') if ($features.ErrorHandling.UseThrowTerminating) { [void]$sb.AppendLine(' $PSCmdlet.ThrowTerminatingError($_)') } else { [void]$sb.AppendLine(' Write-Error $_.Exception.Message') } [void]$sb.AppendLine(' }') [void]$sb.Append(' }') Write-Verbose "Generated $Complexity process block for '$FunctionName'" return $sb.ToString() } catch { Write-Error "Failed to generate process block: $($_.Exception.Message)" $PSCmdlet.ThrowTerminatingError($_) } } end { Write-Debug "End '$($MyInvocation.MyCommand.Name)' at '$(Get-Date)'" } } |