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.

shA.t
  • 16,580
  • 5
  • 54
  • 111
  • 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. – Wiktor Stribiżew Aug 24 '17 at 08:48
  • 2
    What about `()[\S\s]+(<\/command>)`? ;). – shA.t Aug 24 '17 at 08:56
  • so will the regex look like this $regex = '(?s)(\d*).*?()(?s)' – vikram athare Aug 24 '17 at 08:59
  • 7
    [don't parse `xml` with regex](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags). Instead, read as `xml` and either dot index (`$myconfig.topnode.othernode.command`) or [`SelectNode`](https://stackoverflow.com/questions/17894552/editing-web-config-file-using-microsoft-powershell/17899255#17899255) – G42 Aug 24 '17 at 09:10

1 Answers1

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")