5

I have a variables, which returns values from json:

$version = (Get-Content 'package.json' | ConvertFrom-Json).version

This value always goes in x.x.x format. It can be either 0.0.3 or 1.123.23 value.

My question is - how to increase the only patch value? E.g. I need to have 0.0.4 or 1.123.24 output values after transform.

Vasyl Stepulo
  • 1,493
  • 1
  • 23
  • 43

4 Answers4

6

Convert to a [version] object:

# read existing version
$version = [version](Get-Content 'package.json' | ConvertFrom-Json).version

# create new version based on previous with Build+1
$bumpedVersion = [version]::new($version.Major, $version.Minor, $Version.Build + 1)

Alternatively, split the string manually:

$major,$minor,$build = $version.Split('.')

# increment build number
$build = 1 + $build

# stitch back together
$bumpedVersion = $major,$minor,$build -join '.'
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • Well, your method is awesome, but for the first case I need to have a string - how I can achieve this? Out-String doesn't help http://prntscr.com/recmwd – Vasyl Stepulo Mar 10 '20 at 17:39
  • 2
    @VasiliyVegas `"$bumpedVersion"` or `$bumpedVersion -as [string]` or `$bumpedVersion.ToString()` will all do :) – Mathias R. Jessen Mar 10 '20 at 17:51
2

To complement Mathias' helpful answer with a concise alternative based on the -replace operator:

# PowerShell [Core] only (v6.2+) - see bottom for Windows PowerShell solution.
PS> '0.0.3', '1.123.3' -replace '(?<=\.)[^.]+$', { 1 + $_.Value }
0.0.4
1.123.4
  • Regex (?<=\.)[^.]+$ matches the last component of the version number (without including the preceding . in the match).

  • Script block { 1 + $_.Value } replaces that component with its value incremented by 1.

For solutions to incrementing any of the version-number components, including proper handling of [semver] version numbers, see this answer.


In Windows PowerShell, where the script-block-based -replace syntax isn't supported, the solution is more cumbersome, because it requires direct use of the .NET System.Text.RegularExpressions.Regex type:

PS> '0.0.3', '1.123.3' | foreach { 
       [regex]::Replace($_, '(?<=\.)[^.]+$', { param($m) 1 + $m.Value })
    }
0.0.4
1.123.4
mklement0
  • 382,024
  • 64
  • 607
  • 775
1
C:\> $v = "1.2.3"
C:\> $(($v -split "\.")[0..1] + "$([int](($v -split '\.') |Select-Object -Index 2) +1)") -join "."
midacts
  • 196
  • 6
1

Try this:

$build = [int]($version.split(".")[2])+1
$bumpedversion = $version.split(".")[0], $version.split(".")[1], $build -join "."
Wasif
  • 14,755
  • 3
  • 14
  • 34