2015-12-10 38 views
0

使用从用户输入中获取FQDN的脚本,然后输入该服务器和域名,并在模式ID=之后将其添加到文本文件中。查找并替换txt文件中的字符串的一部分

有一个文本文件,里面是一条线,有ID=[some number]。 我想要一个cmdlet将在ID=之后找到的[some number]更改为我定义的2个变量。从安斯加尔

解决方案:

$name,$domain,$rest = $serverName.split('.',3) 
(get-content 'c:\file.txt') -replace "(ID=).*", "`$1$domain$name" | set-content 'c:\file.txt' 

使用PowerShell V2。

回答

1

只需更换与变量的内容数量,然后写的文字回文件:

(Get-Content 'C:\file.txt') -replace '(ID=)\[\d*\]', "`$1$domain$name" | 
    Set-Content 'C:\file.txt'