使用正则表达式和Powershell更新匹配的版本



当第一个点之前的字符为 1 时,一切正常,但是当符号大于 1 时,我正在努力寻找解决方案。任何提示/帮助都值得赞赏:)

$patternRegx = '^(d+.){3}(d+)$'
$pathToVersion = "D:version.txt" ---> #contains string "1.2.3.4"
$appVersion = Get-Content $pathToVersion
if ($appVersion -match $patternRegx) {
Write-Host "Version $appVersion is valid" -BackgroundColor Blue
Write-Host "Updating the version.." -BackgroundColor Blue
$updateMajor = [int]::Parse($appVersion[0]) + 1
$appVersion = $appVersion -replace '^d+.',"$updateMajor." | Set-Content -Path $pathToVersion
$appVersion = Get-Content $pathToVersion
Write-Host "$appVersion" -BackgroundColor Blue
}
else {
Write-Host "Invalid version!"
}

这里有两种方法可以做你想做的事情:

第一种方法使用 System.Version 对象来递增 Major 元素:

$patternRegx   = '^(d+.){3}(d+)$'
$pathToVersion = "D:version.txt" #contains string "1.2.3.4"
$appVersion    = Get-Content $pathToVersion
if ($appVersion -match $patternRegx) {
Write-Host "Version $appVersion is valid" -BackgroundColor Blue
# convert into a System.Version object
$current = [version]$appVersion
# create new version by incrementing the $current.Major element
$newVersion = [version]::new($current.Major + 1, $current.Minor, $current.Build, $current.Revision)
Write-Host "Updating the version.." -BackgroundColor Blue
$newVersion.ToString() | Set-Content -Path $pathToVersion
# prove the new version is stored correctly
$appVersion = Get-Content $pathToVersion
Write-Host "$appVersion" -BackgroundColor Blue
}
else {
Write-Host "Invalid version!"
}

作为替代方案,您可以使用-split-join如下:

if ($appVersion -match $patternRegx) {
Write-Host "Version $appVersion is valid" -BackgroundColor Blue
# split into integers
$version = [int[]]($appVersion -split '.')
# incrementing the first element
$version[0]++
Write-Host "Updating the version.." -BackgroundColor Blue
# join the array with dots
$version -join '.' | Set-Content -Path $pathToVersion
# prove the new version is stored correctly
$appVersion = Get-Content $pathToVersion
Write-Host "$appVersion" -BackgroundColor Blue
}
else {
Write-Host "Invalid version!"
}

希望有帮助

> @Theo 谢谢你的帮助。

我昨天已经设法解决了它,但我会尝试你的方式太必要:)完整代码为:

$patternRegx = '^(d+.){3}(d+)$'
$pathToVersion = "D:version.txt"
$appVersion = Get-Content $pathToVersion

if ($appVersion -match $patternRegx) {
Write-Host "Version $appVersion is valid." -BackgroundColor DarkGreen
Write-Host "Updating the version.." -BackgroundColor Blue
$majorVersion = $appVersion.Split(".")
$updateMajor = [int]::Parse($majorVersion[0]) + 1
$majorVersion = $majorVersion -join "." -replace '^d+.',"$updateMajor." | Set-Content -Path $pathToVersion
$newVersion = Get-Content $pathToVersion
Write-Host "$newVersion" -BackgroundColor Blue
}
else {
Write-Host "Invalid version!" -BackgroundColor Red
}

最新更新