I want to remove the following text in my .csproj files
<EmbeddedResource Include="Properties\licenses.licx" />.
So in other words replace with ' '. I have tried the following
$c = (($_ | Get-Content)) | Out-String
if ($c.Contains("<EmbeddedResource Include=""Properties\licenses.licx"" />"))
{
$c = $c -replace "<EmbeddedResource Include=""Properties\licenses.licx"" />",""
It says The regular expression pattern is not valid. How can i set regular expressions here ?
2 Answers 2
You can do the following:
$content = Get-Content $File
$replace = [regex]::Escape('<EmbeddedResource Include="Properties\licenses.licx" />')
$content = $content -replace $replace
Using [regex]::Escape() will create an escaped regex string for you automatically. Since you want to replace the match with an empty string, you can just do a simple string -replace value syntax and forego the replacement string. Only the matched strings will be replaced. Unmatched strings will remain unchanged. If you use single quotes around the regex string (or any string), everything inside will be treated as a literal string making capturing the inner quotes simpler.
As an aside, you don't technically need to set Get-Content to a variable first. The entire command can be the LHS of -replace.
$content = (Get-Content $File) -replace $replace
Comments
All you are missing is a \ to escape the \ file path separator. You could also add \r\n to avoid an empty line in your project file.
# $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" />
Comments
Explore related questions
See similar questions with these tags.