如何解决使用Powershell对.cs文件进行更改
我正在尝试使用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,int? param2 = null)"| Set-Content $target
代码打开了文件(文件中的其他一些更改有效),但未对我的函数进行任何更改
我尝试在圆括号前放置“ \”,以在获取文件内容时使用-Raw命令,如下所示:(Get-Content $target) | ForEach-Object { $_ -replace "MyFunction (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代码进行更改?
解决方法
-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,了解有关如何转义模式的更多信息
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。