Home > Net >  replace match group using regex powershell
replace match group using regex powershell

Time:03-09

I am trying to setup a PowerShell script that would replace a matching string from my GlobalAssemblyInfo.cs file. I am basically looking to update the Version number via powershell so I can do that in a post build automatically. Anyways, the input string from the cs file is this:

//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using System.Runtime.InteropServices;


[assembly: System.Reflection.AssemblyVersion("1.1.31.0")]
[assembly: System.Reflection.AssemblyCompany("Name")]
[assembly: System.Reflection.AssemblyProduct("Name")]
[assembly: System.Reflection.AssemblyCopyright("Name")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

My PowerShell script that I am attempting is this:

$file = "C:\users\konrad\desktop\GlobalAssemblyInfo.cs"
$pattern = '^\[assembly: System\.Reflection\.AssemblyVersion\("(.*)"\)\]'
$version = '2.0.0.0_delta'

(Get-Content $file).replace($pattern, "$1 $version") | Set-Content $file

Again, the idea is to get the version number that is between the ("") and replace it with a string called $version. I am not getting any errors with the above code. It simply doesn't work. Any ideas would be appreciated.

Cheers!

EDIT:

@Abraham Zinala suggested using -replace instead. I tried that.

(Get-Content $file) -replace $pattern, "$1$version" | Set-Content $file

This replaces this:

[assembly: System.Reflection.AssemblyVersion("1.1.31.0")]

into this:

2.0.0.0_delta

What I want is this:

[assembly: System.Reflection.AssemblyVersion("2.0.0.0_delta")]

CodePudding user response:

Abraham's helpful comment already pointed out the key issue, .Replace(..) string method is not regex compatible, you can use the -replace operator for regex replacements. As for your desired output, you could use the following pattern:

$pattern = '(?m)(^\[assembly: System\.Reflection\.AssemblyVersion\(")[\d.] '
$version = '2.0.0.0_delta'

(Get-Content $file -Raw) -replace $pattern, "`${1}$version" | Set-Content ...

See https://regex101.com/r/VLoUN2/1 for explanation.

You might want to change [\d.] for [\w\d.] in case the version you're looking to replace could also contain word characters and underscores.

  • Related