1

I am looking for a way to convert a string 1.2.0 to an int so that I could increment the last digit. Final result should be 1.2.1

$values = '1.2.0'

$after = $values.split('.');

$result = [int]$after;

# TODO increment the last decimal value, result should be 1.2.3

$result
mklement0
  • 382,024
  • 64
  • 607
  • 775
bob smith
  • 63
  • 8

2 Answers2

6

It is surprising that the System.Version type doesn't support methods for incrementing the components of a version number (neither does the the PowerShell Core-only System.Management.Automation.SemanticVersion type).

Here's a PSv5+ solution:

$versionString = '1.2.0'

$version = [version] $versionString

$versionStringIncremented = [string] [version]::new(
  $version.Major,
  $version.Minor,
  $version.Build + 1
)

# $versionStringIncremented now contains '1.2.1'

If you wanted to wrap that up in a function that allows incrementing any of the components, while setting all lower components to 0 or, in the case of .Revision, to undefined (reported as -1):

function Increment-Version {
  param(
    [Parameter(Mandatory)]
    [version] $Version
    ,
    [ValidateSet('Major', 'Minor', 'Build', 'Revision')]
    [string] $Component = 'Revision'
  )

  $useRevision = $Version.Revision -ne -1 -or $Component -eq 'Revision'

  $Major, $Minor, $Build, $Revision =
    $Version.Major, $Version.Minor, $Version.Build, $Version.Revision

  switch ($Component) {
    'Major' { $Minor = $Build = 0 }
    'Minor' { $Build = 0 }
  }

  Set-Variable $Component (1 + (Get-Variable -ValueOnly $Component))

  if ($useRevision) {
    [version]::new(
      $Major,
      $Minor,
      $Build,
      $Revision
    )
  } else {
    [version]::new(
      $Major,
      $Minor,
      $Build
    )
  }

}

Your command would then simplify to:

# -> '1.2.1'
$versionStringIncremented = [string] (Increment-Version 1.2.0 -Component Build)

# -> '1.3.0'
$versionStringIncremented = [string] (Increment-Version 1.2.7 -Component Minor)
mklement0
  • 382,024
  • 64
  • 607
  • 775
0

This small snippet was a way to just figure out how to increment the last digit of my build number when I call the json string using tfs api.

I found a solution, I was trying to automate my TFS build version number to increment after every build during my build task. I will create variables for my build version numbers and follow this method.

I used these guides to create my script:

https://platform.deloitte.com.au/articles/how-to-automate-incrementing-project-build-numbers-in-vsts

http://devbraino.com/2017/09/25/auto-package-vsts-custom-build-task/

$first = '1'
$second = '2'
$third = '0'

$currentVersion = "$($first).$($second).$($third)"

$third = "$([System.Convert]::ToInt32($third) + 1)"
[string]$newVersionNumber = "$($first).$($second).$($third)"

$newVersionNumber
bob smith
  • 63
  • 8