2

Let's say I have this:

[System.Version]::new(1, 2, 3, 4)

How can I convert it into "3.4"? I'm interested in piping it if possible to avoid having to create an intermediary variable.

7 Answers 7

3

this is ugly but it works inline fairly well. it uses the .Split() option to put the results into a specific number of items with all the remaining ones added to the last one.

([version]'1.2.3.4').ToString().Split('.', 3)[-1]

output = 3.4

Sign up to request clarification or add additional context in comments.

Comments

3

Another ugly but inline solution, uses ForEach-Object to get at the piped reference.

[System.Version]::new(1, 2, 3, 4) | ForEach-Object { "$($_.Build).$($_.Revision)" }

Comments

2

You could also consider creating a Function for this that worked via Pipeline input:

Function ConvertTo-BuildRevision {
    Param(
        [Parameter(ValueFromPipeline)]
        [system.version]
        $Version
    )
    Process {
        Return "$($Version.Build).$($Version.Revision)"
    }
}

[System.Version]::new(1, 2, 3, 4) | ConvertTo-BuildRevision

This is obviously a lot more lines of code, but if you were performing this kind of conversion multiple times in your code would look a lot cleaner.

Comments

1

Here's another option, that uses Select-Object and a calculated property to get the result you want as a property named BR which is then returned:

([System.Version]::new(1, 2, 3, 4) | Select @{N ='BR'; E = { "$($_.Build).$($_.Revision)" }}).BR

Comments

0

If you set it to a variable, you can do this:

$version = [System.Version]::new(1, 2, 3, 4)
"$($version.Build).$($version.Revision)"

Comments

0

A regex-based solution with the -replace operator:

PS> [System.Version]::new(1, 2, 3, 4) -replace '^(.+?\.){2}'
3.4

Comments

0

Using a wrapper and adding a ScriptProperty:

Function New-Version {
    $Version = New-Object System.Version $Args
    $Version | Add-Member ScriptProperty BuildRevision {"$($This.Build).$($This.Revision)"} 
    Write-Output $Version
}

(New-Version 1 2 3 4).BuildRevision
3.4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.