如何使用Powershell替换文件中的文本?

时间:2019-10-09 01:20:09

标签: powershell powershell-3.0 powershell-4.0

我要在.csproj文件中删除以下文本

    <EmbeddedResource Include="Properties\licenses.licx" />. 

因此换句话说就是''。我尝试了以下

$c = (($_ | Get-Content)) | Out-String
if ($c.Contains("<EmbeddedResource Include=""Properties\licenses.licx"" />"))
{
  $c = $c -replace "<EmbeddedResource Include=""Properties\licenses.licx"" />",""

它表示正则表达式模式无效。 我如何在这里设置正则表达式?

2 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

$content = Get-Content $File
$replace = [regex]::Escape('<EmbeddedResource Include="Properties\licenses.licx" />')
$content = $content -replace $replace

使用[regex]::Escape()将自动为您创建一个转义的正则表达式字符串。由于要用空字符串替换匹配项,因此只需执行简单的string -replace value语法并放弃替换字符串即可。仅匹配的字符串将被替换。不匹配的字符串将保持不变。如果在正则表达式字符串(或任何字符串)周围使用单引号,则内部的所有内容都将被视为文字字符串,从而使捕获内部引号更加简单。

顺便说一句,从技术上讲,您无需首先将Get-Content设置为变量。整个命令可以是-replace的LHS。

$content = (Get-Content $File) -replace $replace

答案 1 :(得分:0)

您所缺少的只是一个\,以逃避\文件路径分隔符。您也可以添加\r\n以避免在项目文件中出现空行。

# $content = Get-Content "File.csproj"

$content = "
<EmbeddedResource Include=`"SomeFile.txt`" />
<EmbeddedResource Include=`"Properties\licenses.licx`" />
<EmbeddedResource Include=`"SomeOtherFile.txt`" />
"

$content = $content -replace '<EmbeddedResource Include="Properties\\licenses.licx" />\r\n',''

# $content | Out-File "File.csproj"

Write-Host $content

# Output
# <EmbeddedResource Include="SomeFile.txt" />
# <EmbeddedResource Include="SomeOtherFile.txt" />