Powershell Increment value by 0.0.1

荒凉一梦 提交于 2020-05-13 14:32:52

问题


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.


回答1:


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 '.'



回答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



回答3:


C:\> $v = "1.2.3"
C:\> $(($v -split "\.")[0..1] + "$([int](($v -split '\.') |Select-Object -Index 2) +1)") -join "."



回答4:


Try this:

$build = [int]($version.split(".")[2])+1
$bumpedversion = $version.split(".")[0], $version.split(".")[1], $build -join "."


来源:https://stackoverflow.com/questions/60622782/powershell-increment-value-by-0-0-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!