12

I have a text file that contains only one line with a version number of my application. An example would be 1.0.0.1. I would like to increment the build number. Using my example I would get the output 1.0.0.2 in the same text file.

How can I do it with PowerShell?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mfuxi
  • 181
  • 1
  • 2
  • 9

3 Answers3

21

This might be over kill, but it shows the use of the type [version] which will save the need to do string manipulation.

$file = "C:\temp\File.txt"
$fileVersion = [version](Get-Content $file | Select -First 1)
$newVersion = "{0}.{1}.{2}.{3}" -f $fileVersion.Major, $fileVersion.Minor, $fileVersion.Build, ($fileVersion.Revision + 1)
$newVersion | Set-Content $file

The file contents after this would contain 1.0.0.2. The unfortunate part about using [version] is that the properties are read-only, so you can't edit the numbers in place. We use the format operator to rebuild the version while incrementing the Revision by one.

On the off chance there is some whitespace or other hidden lines in the file we ensure we get the first line only with Select -First 1.

One of several string manipulation based solution would be to split the contents into an array and then rebuild it after changes are made.

$file = "C:\temp\File.txt"
$fileVersion = (Get-Content $file | Select -First 1).Split(".")
$fileVersion[3] = [int]$fileVersion[3] + 1
$fileVersion -join "." | Set-Content $file

Split the line on its periods. Then the last element (third) contains the number you want to increase. It is a string so we need to cast it as an [int] so we get an arithmetic operation instead of a string concatenation. We then rejoin with -join.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Matt
  • 45,022
  • 8
  • 78
  • 119
3
$versionFile = Get-Content -Path "c:\temp\testing.txt"
$version = [version]($versionFile)

$newVersion = New-Object -TypeName System.Version -ArgumentList $version.Major, $version.Minor, $version.Build, ($version.Revision + 1)
$newVersion | Set-Content -Path "c:\temp\testing.txt"
MonkeyDreamzzz
  • 3,978
  • 1
  • 39
  • 36
  • 1
    @Matt your solution also looks great but indeed, the `New-Object` avoids having to parse your own version number. Would be nice if `System.Version` had `NextRevision()`, `NextBuild()`,... methods that returned a new Version – MonkeyDreamzzz May 12 '15 at 15:40
  • When I saw this question I thought it would be a great use for `[version]` until I got the read-only errors. – Matt May 12 '15 at 15:41
0

One more string variation that removes the redundant assignment to the array member and includes a reminder on how to address the last element of an array. I think it is a little cleaner.

$file="C:\scripts\assemblyVersion.txt"
$versionparts = (get-content -Path $file).split('.')
([int]$versionparts[-1])++
$versionparts -join('.') | set-content $file
housten
  • 126
  • 9