使用regex和Powershell更新匹配的版本

时间:2020-05-23 22:53:16

标签: 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!"
}

2 个答案:

答案 0 :(得分:0)

以下两种方法可以完成您想要的事情:

第一种方法使用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!"
}

希望有帮助

答案 1 :(得分:0)

@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
}