Background
I'm trying to write a small utility that searches through a file to find all instances of lines that look like this:
[SecuredEndpoint(widgets.UpdateWidget)]
And make it look like this:
//[SecuredEndpoint(widgets.UpdateWidget)]
[AllowAnonymous]
So far, I have the following script - haven't written it back to the file yet.. just doing everything in memory first.
#Find and comment out all [SecuredEndpoint] attributes
(Get-Content -path .\TestController.cs -Raw) -replace '\[SecuredEndpoint','//\[SecuredEnpoint' | Foreach-Object {
$_ # send the current line to output
if ($_ -match "//[SecuredEndpoint")
{
#Add Lines after the selected pattern
"[AllowAnonymous]"
}
}
It correctly comments out all the various the SecuredEndpoint lines, but it doesn't insert a new line afterwards. So the results look like this:
[Route("widgets/")]
[HttpGet]
//[SecuredEnpoint(mywidget.GetAll)]
public List<Widgets> GetWidgets()
{
}
[Route("widgets/)]
[HttpPost]
//[SecuredEnpoint(mywidget.Create)]
public List<Widgets> GetWidgets()
{
}
I don't get any errors.
Questions
What am i missing in the logic to make it insert the new line? Once that's fixed, I'm assuming I can do something like this to actually save the contents back to the file:
(Get-Content -path .\TestController.cs -Raw) -replace '\[SecuredEndpoint','//[SecuredEnpoint' | Foreach-Object {
$_ # send the current line to output
if ($_ -match "//\[SecuredEndpoint")
{
#Add Lines after the selected pattern
"[AllowAnonymous]"
}
} Set-Content .\TestController.cs
Please and thanks!
"//[SecuredEndpoint"is not a valid regex pattern, it needs to be"//\[SecuredEnpoint".Replace('[SecuredEndpoint(widgets.UpdateWidget)]', "//[SecuredEndpoint(widgets.UpdateWidget)]`n[AllowAnonymous]")and read the file as single multiline string with-Raw