2

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

}

2
  • Try $RegularExpression = [regex] 'AssemblyVersion\("(\d(?:\.\d){3})"\)' Commented Jul 12, 2021 at 12:40
  • please add a few lines of your $fileContent collections to see what works with that specific data. Commented Jul 12, 2021 at 12:41

1 Answer 1

1
  • 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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.