Bakula33
Bakula33

Reputation: 75

Regex in powershell for getting assembly version number

I am trying to create a script that will find and return the assembly version from the solution. It covers some of the test scenarios, but I cannot find the correct regex that will check is the version in correct format (1.0.0.0 is ok, but 1.0.o.0) and that contains 4 digits? Here is my code.

function Get-Version-From-SolutionInfo-File($path="$pwd\SolutionInfo.cs"){
$RegularExpression = [regex] 'AssemblyVersion\(\"(.*)\"\)'
$fileContent = Get-Content -Path $path
foreach($content in $fileContent)
{
    $match = [System.Text.RegularExpressions.Regex]::Match($content, $RegularExpression)
    if($match.Success) {
        $match.groups[1].value
    }
}

}

Upvotes: 2

Views: 528

Answers (1)

mklement0
mklement0

Reputation: 437353

  • Change your greedy capture group, (.*), to a non-greedy one, (.*?), so that only the very next " matches.

    • The alternative is to use ([^"]*)
  • To verify if a string contains a valid (2-to-4 component) version number, simply cast it to [version] (System.Version).

Applied to your function, with optimized extraction of the capture group via the -replace operator:

function Get-VersionFromSolutionInfoFile ($path="$pwd\SolutionInfo.cs") {
  try {
    [version] $ver = 
      (Get-Content -Raw $path) -replace '(?s).*\bAssemblyVersion\("(.*?)"\).*', '$1'
  } catch {
    throw
  }
  return $ver
}

Upvotes: 1

Related Questions