我正在尝试设置一个 PowerShell 脚本来替换 GlobalAssemblyInfo.cs 文件中的匹配字符串。我基本上希望通过 powershell 更新版本号,这样我就可以在构建后自动执行此操作。无论如何,cs 文件的输入字符串是这样的:
//------------------------------------------------------------------------------
// <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)]
我正在尝试的 PowerShell 脚本是这样的:
$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
同样,我们的想法是获取 ("")
之间的版本号,并将其替换为名为 $version 的字符串。上面的代码我没有收到任何错误。这根本行不通。任何想法将不胜感激。
干杯!
编辑:
@Abraham Zinala 建议使用 -replace
代替。我试过了。
(Get-Content $file) - 替换 $pattern, "$1$version"|设置内容$file
这取代了这个:
[程序集:System.Reflection.AssemblyVersion("1.1.31.0")]
进入此:
2.0.0.0_delta
我想要的是这样的:
[程序集:System.Reflection.AssemblyVersion("2.0.0.0_delta")]
最佳答案
Abraham's helpful comment已经指出了关键问题,.Replace(..)
string method与正则表达式不兼容,您可以使用 -replace
operator用于正则表达式替换。至于您想要的输出,您可以使用以下模式:
$pattern = '(?m)(^\[assembly: System\.Reflection\.AssemblyVersion\(")[\d.]+'
$version = '2.0.0.0_delta'
(Get-Content $file -Raw) -replace $pattern, "`${1}$version" | Set-Content ...
参见https://regex101.com/r/VLoUN2/1进行解释。
您可能需要将 [\d.]+
更改为 [\w\d.]+
如果您要替换的版本也可能包含单词字符和下划线。
关于powershell - 使用正则表达式 + powershell 替换匹配组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71399918/