0

I am trying to modify config.xml.
config.xml content is

<command>
some lines here 2
</command>
some lines here 3

So I want to replace the content between <command> and </command>. Here is what I tried doing

$Replace = Get-Content D:\Temp\Replace.txt
$ReplaceWith = Get-Content D:\Temp\ReplaceWith.txt

$regex = '(<command>\d*).*?(</command>\d*)'
$Replace -replace $regex, $ReplaceWith

But its not working. Need help.

4
  • 1
    Use -Raw with Get-Content and also add (?s) at the regex start. Also, if your replaceWith.txt contains plain text (not a specifically formatted regex replacement string) and if you have $ in the replacement, you need to double them and remove \d* and parentheses. Commented Aug 24, 2017 at 8:48
  • 2
    What about (<command>)[\S\s]+(<\/command>)? ;). Commented Aug 24, 2017 at 8:56
  • so will the regex look like this $regex = '(?s)(<command>\d*).*?(</command>)(?s)' Commented Aug 24, 2017 at 8:59
  • 7
    don't parse xml with regex. Instead, read as xml and either dot index ($myconfig.topnode.othernode.command) or SelectNode Commented Aug 24, 2017 at 9:10

1 Answer 1

0

Thanks gms0ulman. I was able to do this using reading as xml in powershell, below was the code

$ReplaceWith = Get-Content C:\psscript.ps1 -Raw
[xml]$ConfigXml = Get-Content "c:\config.xml" -Raw
$SelectCommandNode = $ConfigXml.SelectSingleNode("//command")
$SelectCommandNode.InnerText = $ReplaceWith
$ConfigXml.Save("c:\config.xmll")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.