[英]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. 到下一个\
之间的任何内容\
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.