Modules/businessdev.ALbuild.Core/Public/ConvertTo-BcVersion.ps1
|
function ConvertTo-BcVersion { <# .SYNOPSIS Converts a version string into a normalised 4-part [version]. .DESCRIPTION Business Central versions are four-part (Major.Minor.Build.Revision). This helper accepts partial versions (e.g. "25", "25.1") and pads them to four parts, and tolerates NuGet/SemVer pre-release or build-metadata suffixes (e.g. "1.0.0-beta+sha") by using only the numeric core for comparison. .PARAMETER InputObject The version string to convert. Accepts pipeline input. .PARAMETER Strict When set, an empty or non-numeric value throws instead of returning 0.0.0.0. .EXAMPLE ConvertTo-BcVersion '25.1' Returns [version] 25.1.0.0 .EXAMPLE '1.0.0-beta' | ConvertTo-BcVersion Returns [version] 1.0.0.0 .OUTPUTS System.Version #> [CmdletBinding()] [OutputType([version])] param( [Parameter(Mandatory, ValueFromPipeline)] [AllowNull()] [AllowEmptyString()] [string] $InputObject, [switch] $Strict ) process { $raw = if ($null -eq $InputObject) { '' } else { $InputObject.Trim() } if ([string]::IsNullOrWhiteSpace($raw)) { if ($Strict) { throw "Cannot convert an empty value to a Business Central version." } return [version]'0.0.0.0' } # Drop a SemVer/NuGet pre-release or build-metadata suffix; keep the numeric core. $core = ($raw -split '[-+]', 2)[0].Trim() if ($core -notmatch '^\d+(\.\d+){0,3}$') { $leading = [regex]::Match($core, '^\d+(\.\d+){0,3}') if (-not $leading.Success) { if ($Strict) { throw "'$raw' is not a valid Business Central version." } return [version]'0.0.0.0' } if ($Strict) { throw "'$raw' is not a valid Business Central version." } $core = $leading.Value } $parts = [System.Collections.Generic.List[string]]::new() $parts.AddRange([string[]]$core.Split('.')) while ($parts.Count -lt 4) { $parts.Add('0') } return [version]("{0}.{1}.{2}.{3}" -f $parts[0], $parts[1], $parts[2], $parts[3]) } } |