【问题标题】:Make changes to a .cs file using powershell使用 powershell 更改 .cs 文件
【发布时间】:2020-12-19 18:07:47
【问题描述】:

我正在尝试使用 PowerShell 在 .cs 文件中进行一些替换。
例如我有:

string MyFunction (string param1 = null, int? param2 = null) 我需要转至:
string MyFunction (byte[] _file = null, string param1 = null, int? param2 = null)

现在进行此更改的代码部分如下所示:
$target = "Path\File.cs" (Get-Content $target) -replace "MyFunction (string param1 = null, int? param2 = null)", "MyFunction (byte[] _file = null, string param1 = null, int? param2 = null)"| Set-Content $target

代码打开文件(其中的一些其他更改有效)但它没有对我的函数进行任何更改 我尝试在括号前加一个“\”,以便在获取文件内容时使用 -Raw 命令,如下所示:
(Get-Content $target) | ForEach-Object { $_ -replace "MyFunction (string param1 = null, int? param2 = null)", "MyFunction (byte[] _file = null, string param1 = null, int? param2 = null)" } | Set-Content $target

在同一个文件上,我还有另一个修改来自:
string MyFunction2(param1);
string MyFunction2(_file, param1);
这个替换在我使用时有效:
(Get-Content $target) -replace "MyFunction2\(param1\);", "MyFunction2(_file, param1);"| Set-Content $target

我应该如何编写 PowerShell 代码来进行更改?

【问题讨论】:

    标签: c# powershell replace


    【解决方案1】:

    -replace 是一个正则表达式运算符,您需要转义输入以按原样匹配它 - 否则正则表达式引擎会将 ()? 解释为控制字符:

    $replaceEscaped = [regex]::Escape('string MyFunction (string param1 = null, int? param2 = null)')
    $substitute = 'string MyFunction (byte[] _file = null, string param1 = null, int? param2 = null)'
    
    (Get-Content $target) -replace $replaceEscaped, $substitute
    

    查看about_Regular_Expressions help document 了解更多关于如何转义模式的信息

    【讨论】:

    • 我错过了问号上的转义,添加后它起作用了,谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 2017-12-15
    • 2010-10-02
    相关资源
    最近更新 更多