我正在寻找一种将字符串1.2.0转换为int的方法,以便可以增加最后一位数字。最终结果应为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
最佳答案
令人惊讶的是, System.Version
类型不支持用于增加版本号的组件的方法(PowerShell专用的 System.Management.Automation.SemanticVersion
类型也不支持)。
这是PSv5 +解决方案:
$versionString = '1.2.0'
$version = [version] $versionString
$versionStringIncremented = [string] [version]::new(
$version.Major,
$version.Minor,
$version.Build + 1
)
# $versionStringIncremented now contains '1.2.1'
如果要将其包装在函数中,该函数允许增加任何组件,同时将所有较低的组件设置为
0
,或者在.Revision
的情况下设置为undefined(报告为-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
)
}
}
然后,您的命令将简化为:
# -> '1.2.1'
$versionStringIncremented = [string] (Increment-Version 1.2.0 -Component Build)
# -> '1.3.0'
$versionStringIncremented = [string] (Increment-Version 1.2.7 -Component Minor)
关于powershell - 将字符串转换为int并仅对TFS中的内部版本号递增最后一位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55348768/