Wednesday, 28 August 2013

Powershell: Force immediate evaluation of backreference during replace

Powershell: Force immediate evaluation of backreference during replace

I am running into an error where I am concatenating strings together to
obtain the field I want replaced.
Below is an example of what my script is doing:
$TEXTTOREPLACEWITH= '6Q'
(Get-Content testfile.html) | ForEach-Object { $_ -replace
'(.)\$(STRINGTOREPLACE)(.)', ('$1' +$TEXTTOREPLACEWITH+'$2')
If I ran this against a file that had a line input as follows:
abc$(STRINGTOREPLACE)xyz
I would expect the following output:
abc6Qxyz
Instead, When I run this script the output looks as follows:
$16Qxyz
I'm assuming this is due to the fact that backreferences must not be
resolved until string concatentation is complete. Is there any way in
powershell to go ahead and resolve these backreferences immediately and
avoid the output that I am seeing?
Thanks,
Josh

No comments:

Post a Comment