I have a text file with the following text in:
<ServerAddress>.</ServerAddress>
<ServerDatabase>test</ServerDatabase>
<ServerUsername>jimmy</ServerUsername>
I want to be able to replace the "." with a read-host
entered piece of text. For example change it from <ServerAddress>.</ServerAddress>
to
<ServerAddress>server1</ServerAddress>
The code I have to far works... but it replaces everything in the file to the same string over and over, so in the example from above, it would have replaced everything with <ServerAddress>server1</ServerAddress>
Here is what I have so far:
pushd "C:\PSF\Move to V6\DTT Files"
$configFiles = Get-ChildItem . *.dtt -rec
$servername = Read-Host 'What the server name?'
$regex='(m?)>[^<]+<'
foreach ($file in $configFiles)
{
(Get-Content $file.PSPath) |
Foreach-Object { "<ServerAddress>.</ServerAddress>" -replace $regex, ">$servername<" } |
Set-Content $file.PSPath
}
Don't use regex to replace XML content. Instead, load the file as XML, select the node and set the values:
Example:
[xml]$xml =
@'
<root>
<ServerAddress>.</ServerAddress>
<ServerDatabase>test</ServerDatabase>
<ServerUsername>jimmy</ServerUsername>
</root>
'@
$xml.DocumentElement.ServerAddress = 'newServer'
$xml.Save('yourLocation')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.