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

How can i replace text in a file using Powershell?

我想删除我的 .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"" />",""

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

您可以执行以下操作:

$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

您只缺少一个 \ 来转义 \ 文件路径分隔符。您还可以添加 \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" />