David Allison
David Allison

Reputation: 3

Using regex (or similar) in PowerShell to rearrange extracted version number

I am using the below PowerShell command to extract the File Version parameter from an executable and write to a variable, which is working great (found extraction command here: Get file version in PowerShell)

$ver = [System.Diagnostics.FileVersionInfo]::GetVersionInfo("somefilepath").FileVersion

Using the above, I will usually have a File Version that looks like:

11.2.1617.1

What I would like to achieve is to rearrange and slightly amend that output so that it reads:

11.2.1.617

Note that the "1" has been removed from "1617" and that ".617" and ".1" have then swapped places.

I would like the corrected version number to be stored in a new variable (e.g. $vernew) so that I have both the original value and new value in two different variables. The File Version will change over time, but the format will always be the same (e.g. XX.X.XXX.X).

Can anyone please suggest the most appropriate way of achieving this? Any help would be greatly appreciated.

Upvotes: 0

Views: 690

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174505

For swapping, you can use a simple -replace operation for this:

$ver = $ver -replace '^(\d+)\.(\d+)\.(\d+)\.(\d+)','$1.$2.$4.$3'

This will capture the four groups of numbers and swap the last two ones

But since you need to change one of the captured values, I'd suggest doing it like this instead:

# grab the individual parts
$major,$minor,$build,$revision = $ver -split '\.'

# remove first character from the 3rd block
$build = $build.Substring(1)

# concatenate them in the new order
$newver = $major,$minor,$revision,$build -join '.'

Upvotes: 3

Related Questions