Search code examples
regexpowershellregex-lookaroundslookbehind

PowerShell Issues with getting string from file


Problem

I am working on an automated version control script in powershell and I hit a snag where I am trying pull a line of text from an AssemblyInfo.cs file. However, I can't seem to get it to work as expected despite all my efforts.

After many trial and errors to achieve the results intended, I have come to find the following to get close to what I'm trying to achieve:

# Constants
$Assembly = Get-Item "C:\generalfilepath\*\Assembly.cs"
$regex = '(?<!\/\/ \[assembly: AssemblyVersion\(")(?<=\[assembly: AssemblyVersion\(")[^"]*'

$CurrentVersion = GC $Assembly
$CurrentVersion = $CurrentVersion -match $regex

Write-Host "CurrentVersion = $CurrentVersion

I am expecting to see: CurrentVersion = 1.0.0.0 or something similar, but what I get is: CurrentVersion = [assembly: AssemblyVersion("1.0.0.0")]

I have been searching all over for examples on how to properly utilize regex with PowerShell, but I have not really found anything that contains more than the regex itself... As such, I was hoping someone here could assist me in either steering me in the right direction or point out what I am doing wrong.

Question

Despite the use of the regex filter, I'm getting the entire line instead of just the value I want. How do I ensure the variable stores ONLY the target value using the lookbehind and lookahead regex filters?


Solution

  • You can try:

    C:\> ([string] (Get-Content \AssemblyInfo.cs)) -match 'AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\)'
    True
    

    Afterwards the result shall be store in $Matches[1]

    C:\> $Matches[1]
    6.589.0.123
    

    Be aware to cast the results of Get-Content to [string] otherwise $Matches will be $null. See this answer for a complete description.

    If you want to use a more "greedy" regex like ^\[assembly: AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\) which also includes a check (^\[assembly:) that the string starts with [assembly you've to walk through the [string[]] array Get-Content returns:

    > gc .\AssemblyInfo.cs | % { $_ -match '^\[assembly: AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\)' }
    
    > $Matches[1]
    6.589.0.*
    

    Hope that helps.