0

I am trying to replace "\\Server1-123", but I need to use range of characters because the server name changes and I do not know what it will be next time, how can I go about this?

Below variable is what I tried, but alas, did not work:

$anyvalue = "[^*\*A-Za-z0-9_-.]"

below is the xml value I am working with

"<add key=`"My.Unique.Repository`" value=`"\\Server1-123`" />"

here is the full code:

$con = Get-Content "\\server\c$\Program Files\TEST\IIS\web.config"
$anyvalue = "[^*\\*A-Za-z0-9_-.]"
$stuffIwant = "\\Blah-244"
$con | % { $_.Replace("<add key=`"My.Uniqe.Repository`" value=`"\\Server1-123`" />", "<add key=`"My.Uniqe.Repository`" value=`"$stuffIwant`" />") } | `
Set-Content "\\server\c$\Program Files\TEST\IIS\web.config" -force -Encoding UTF8
John Doe
  • 105
  • 11
  • The `[string]` type's `.Replace()` _method_ only supports _literal_ string replacements. To perform _regex_-based replacements, use the `-replace` _operator_ - see [this answer](https://stackoverflow.com/a/40683667/45375). – mklement0 Jul 04 '20 at 01:57

2 Answers2

1

You can escape a regular expression metacharacter with a backslash (). Like this:

$anyvalue = "^*\*[A-Za-z0-9_\-.]"

Also this regex is better than the previous:

^\\\\[A-Za-z0-9_\-].*
Wasif
  • 14,755
  • 3
  • 14
  • 34
1

Since this is XML, you should not use string replacements on it like you are trying to do, but instead make use of PowerShell's capability to handle XML.

$path        = '\\server\c$\Program Files\TEST\IIS\web.config'
[xml]$config = Get-Content -Path $path -Raw
$stuffIwant  = "\\Blah-244"
$config.SelectNodes("//add[@key='My.Unique.Repository']") | ForEach-Object { $_.SetAttribute("value", $stuffIwant) }
$config.Save($path)
Theo
  • 57,719
  • 8
  • 24
  • 41