0

I am trying to replace some text in a file. Currently I am replacing IP addresses with:

(Get-Content $editfile) | ForEach-Object { $_ -replace "10.10.37.*<", "10.10.37.$BusNet<" } | Set-Content $editfile

This code works well here. However I can't get the code to work with another line:

  <dbserver>SVRNAME</dbserver>

Here is the code I have written for this line:

(Get-Content $editfile) | ForEach-Object { $_ -replace "<dbserver>*</dbserver>", "$DbSVRName" } | Set-Content $editfile

The code above should replace SVRNAME with the DbSVRName. Yet it does not. I know it's simple, and I know I am going to feel dumb afterwards. What am I missing?

While debugging trying to find a solution I found that for some reason it can't see the *

(Get-Content $editfile) | ForEach-Object { $_ -match "<dbserver>*</dbserver>" }

This code reveals all falses results.

3
  • Does it work if you escape your slash? '<dbserver>*<//dbserver>' Commented Jul 23, 2015 at 1:26
  • Er wait, You want it to replace SVRNAME? Use -replace 'SVRNAME'. Commented Jul 23, 2015 at 1:27
  • Chris It does not escape with a //. the SVRNAME can be anything. Commented Jul 23, 2015 at 1:34

1 Answer 1

1

* doesn't capture stuff in regex, you need .* and specifically (.*?)

$str = 'text  <dbserver>SVRNAME</dbserver> text'
$replace = 'foo'

$str -replace '(<dbserver>)(.*?)(</dbserver>)', ('$1'+$replace+'$3')

Output

text  <dbserver>foo</dbserver> text
Sign up to request clarification or add additional context in comments.

2 Comments

That makes a lot of sense. Making each item a variable to search. I did not know this one. Thank you. Do you have a resource on this idea/topic? I would love to learn more about the technique you just showed me.
[1] for playing with regex expressions. Here's a decent post on -replace regex [2], but the magic is mostly a regex thing, not PowerShell in this case. There are lots of regex resources, just do some searches. [1]: regexpal.com [2]: powershell.org/wp/2013/08/29/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.