文本文件中的增量版本 [英] Increment version in a text file

查看:76
本文介绍了文本文件中的增量版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中仅包含一行和我的应用程序的版本号.一个例子是 1.0.0.1.我想增加内部版本号.使用我的示例,我将在同一个文本文件中获得输出 1.0.0.2.

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.

如何使用 PowerShell 执行此操作?

How can I do it with PowerShell?

推荐答案

这可能有点过头了,但它显示了类型 [version] 的使用,这将节省进行字符串操作的需要.

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

此后的文件内容将包含 1.0.0.2.使用 [version] 的不幸之处在于属性是只读的,因此您无法就地编辑数字.我们使用格式运算符来重建版本,同时将 Revision 增加 1.

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.

如果文件中有一些空白或其他隐藏行,我们确保只使用 Select -First 1 获得第一行.

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

按句点分割线.然后最后一个元素(第三个)包含您要增加的数字.它是一个字符串,所以我们需要将它转换为 [int] 以便我们得到一个算术运算而不是字符串连接.然后我们用 -join 重新加入.

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.

这篇关于文本文件中的增量版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆