如何使用Powershell比较两个字符串版本?

时间:2019-06-27 10:06:44

标签: powershell powershell-3.0 azure-powershell

嗨,我有两个以下字符串

$str1 = "Ubuntu 16.04 LTS"
$str2 = "Ubuntu 16.04.6 LTS"
问:

  
      
  1. 如果两者都匹配,那是真的
  2.   
  3. $ str1>“ Ubuntu 16.04 LTS”,那么它是真的
  4.   
  5. $ str1 =“ Ubuntu 16.04.01 LTS”就是真的
  6.   
  7. $ str1 <“ Ubuntu 16.04 LTS”则为假
  8.   
  9. $ str1>“ Ubuntu 16.05 LTS”,则为假
  10.   

2 个答案:

答案 0 :(得分:1)

这是一种使用正则表达式的快速方法:

function Compare-UbuntuVersions {
    param
    (
        [string]$Version1,
        [string]$Version2
    )

    $versionRegex = "(?<Version>\d+\.\d+\.?(\d+)?)";
    if ($Version1 -match $versionRegex)
    {
        $v1 = [version]$matches.Version;
    }
    else
    {
        throw "Invalid version string";
    }

    if ($Version2 -match $versionRegex)
    {
        $v2 = [version]$matches.Version;
    }
    else
    {
        throw "Invalid version string";
    }

    if($v1 -gt $v2)
    {
        Write-Host "$Version1 is greater than $Version2";
        return 1;
    }
    elseif ($v1 -eq $v2) 
    {
        Write-Host "$Version1 is equal to $Version2";
        return 0;
    }
    elseif ($v1 -lt $v2) 
    {
        Write-Host "$Version1 is less than $Version2";
        return 0;
    }
}

$targetVersion = "16.04";
$versions = @(
    "Ubuntu 16.04 LTS",
    "Ubuntu 16.04.01 LTS",
    "Ubuntu 16.04.6 LTS",
    "Ubuntu 16.05 LTS"
)

$versions | % { $null = Compare-UbuntuVersions $_ $targetVersion }

# Ubuntu 16.04 LTS is equal to 16.04
# Ubuntu 16.04.01 LTS is greater than 16.04
# Ubuntu 16.04.6 LTS is greater than 16.04
# Ubuntu 16.05 LTS is greater than 16.04

答案 1 :(得分:1)

使用MehmetSeckin答案的框架,但

  • 按照robdy的建议将版本号转换为[version]类型。
  • 检查版本的主要版本和次要版本。
  • 还要检查Distro字符串和后缀。
  • 输出一个[PSCustomObject]
## Q:\Test\2019\06\27\SO_56788705.ps1
function Compare-UbuntuVersions {
    param(
        [string]$VerString1,
        [string]$VerString2
    )
    $Dist1,[version]$Version1,$Suffix1 = $VerString1 -split ' '
    $Dist2,[version]$Version2,$Suffix2 = $VerString2 -split ' '
    If(($Dist1 -eq $Dist2) -and
       ($Suffix1 -eq $Suffix2) -and
       ($Version1.Major -eq $Version2.Major) -and
       ($Version1.Minor -eq $Version2.Minor)) {
        return $True
    } Else {
        return $False
    }
}

$targetVersion = "Ubuntu 16.04 LTS"

$versions = @(
    "Ubuntu 16.04 LTS",
    "Ubuntu 16.04.01 LTS",
    "Ubuntu 16.04.6 LTS",
    "Ubuntu 16.05 LTS"
)

$versions | ForEach-Object { 
   [PSCustomObject]@{
       Target = $targetVersion
       Version= $_
       Match  = Compare-UbuntuVersions $targetVersion $_
   }
}

示例输出:

> Q:\Test\2019\06\27\SO_56788705.ps1

Target           Version             Match
------           -------             -----
Ubuntu 16.04 LTS Ubuntu 16.04 LTS     True
Ubuntu 16.04 LTS Ubuntu 16.04.01 LTS  True
Ubuntu 16.04 LTS Ubuntu 16.04.6 LTS   True
Ubuntu 16.04 LTS Ubuntu 16.05 LTS    False