lib/TMD.Utility.ps1

function ConvertTo-SemanticVersion {
    <#
    .SYNOPSIS
    Converts a string to a semantic version object
     
    .DESCRIPTION
    This function attempts to convert the given string into a semantic
    version object with Major, Minor, Patch, PreReleaseLabel and BuildLabel properties
     
    .PARAMETER VersionString
    The string to be converted
     
    .EXAMPLE
    ConvertTo-SemanticVersion -VersionString '~1.2.6'
     
    .OUTPUTS
    A System.Management.Automation.SemanticVersion object is output. When the string
    parsing was unsuccessful, a SemanticVersion object with a value 0.0.0 is returned
    #>


    [CmdletBinding()]
    [OutputType([System.Management.Automation.SemanticVersion])]
    param (
        [Parameter(Mandatory = $true, 
                   Position = 0,
                   ValueFromPipeline = $true)]
        [String]$VersionString
    )

    process {
        # Remove the non-number characters
        $VersionString = $VersionString.Trim().Replace('^','').Replace('~','')

        # Initialize a 0.0.0 version object
        $Version = [System.Management.Automation.SemanticVersion]::new(0)

        # Attempt to parse the string into a version
        [void][System.Management.Automation.SemanticVersion]::TryParse($VersionString, [ref]$Version)

        $Version
    }
}