Search code examples
xmlpowershellunc

Replace server name in UNC path using PowerShell


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?


Solution

  • 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:

    1. the initial \\
    2. anything between 1. upto the next \
    3. the first \ and anything after

    Group 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.