replace match group using regex + powershell
Asked Answered
H

1

5

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")]

Hillard answered 8/3, 2022 at 18:30 Comment(1)
Pretty sure .Replace() is literal. You probably meant -Replace.Intervalometer
O
9

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.

Ovoid answered 8/3, 2022 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.