I'm working with the XML
configuration file which contains the UNC
path:
[xml]$config = Get-Content $file
$UNC = ($config.configuration.unc.value)
Where $UNC
then equals \\dev.local\share\shared
I need to replace the server name dev.local
(whose name is unknown) in the $UNC
variable with prod.local
using Powershell.
What is the best approach to achieve this?
You can use -replace
with a regular expression:
PS C:\Users\robin> $unc = '\\dev.local\share\shared'
PS C:\Users\robin> $server = 'prod.local'
PS C:\Users\robin> $newUnc = $unc -replace '(\\\\)([a-z\.]+)(\\*)', "`$1$server`$3"
PS C:\Users\robin> $unc
\\dev.local\share\shared
PS C:\Users\robin> $newUnc
\\prod.local\share\shared
The regular expression is matching 3 groups:
\\
\
\
and anything afterGroup 2 is replace with the value of the variable $server
set to prod.local
in this example.
The replace syntax uses double quotes so $server
is evaluated, and the backticks around the capture groups make them work as substitutions from the regular expression.