简体   繁体   English

使用 PowerShell 替换 UNC 路径中的服务器名称

[英]Replace server name in UNC path using PowerShell

I'm working with the XML configuration file which contains the UNC path:我正在使用包含UNC路径的XML配置文件:

[xml]$config = Get-Content $file
$UNC = ($config.configuration.unc.value)

Where $UNC then equals \\dev.local\share\shared其中$UNC然后等于\\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.我需要使用prod.local$UNC变量中的服务器名称dev.local (其名称未知)替换为 prod.local。

What is the best approach to achieve this?实现这一目标的最佳方法是什么?

You can use -replace with a regular expression:您可以将-replace与正则表达式一起使用:

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:正则表达式匹配 3 个组:

  1. the initial \\最初的\\
  2. anything between 1. upto the next \ 1. 到下一个\之间的任何内容
  3. the first \ and anything after第一个\和之后的任何内容

Group 2 is replace with the value of the variable $server set to prod.local in this example.在此示例中,将组 2 替换为设置为prod.local的变量$server的值。

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.替换语法使用双引号,因此$server被评估,捕获组周围的反引号使它们作为正则表达式的替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM