regexpowershellassemblyversions

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

}


Solution

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