I am doing find and replace a string in attribute of xml file using powershell. The strings are properly replaced [I verified it by displaying
"After replace $($Item.Node.$attribute)"
] but in the config file it is not reflected. Seems like it is not saving with latest values properly. I tried all the possibilities but still mysteriously it is not saving. I am using powershell version 2.
function Set-XMLAttribute
{
[CmdletBinding()]
[OutputType([int])]
Param
(
# webconfig file full path
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0)]
[string]$Path,
# Param2 help description
[string] $xPath,
[string] $attribute,
[string] $valueToFind,
[string] $ValueToReplace
)
Begin { }
Process
{
try
{
If ( Test-path -Path $Path)
{
#Loading the file
$xml = New-Object -TypeName XML
$xml.Load($Path)
# Getting all the values
$Items = Select-Xml -Path $Path -XPath $xPath
ForEach ($Item in $Items)
{
$Item.Node.$attribute
If ($($Item.Node.$attribute).Contains($valueToFind) ){
"Before Replace the value $($Item.Node.$attribute)"
$Item.Node.$attribute = $($Item.Node.$attribute) -Replace "$valueToFind","$ValueToReplace"
}
Else {
Write-Error "$valueToFind not available"
}
}
"After replace $($Item.Node.$attribute)"
"Saving the $Path"
$xml.Save((Resolve-Path "$Path"))
}
Else
{
Write-Error "$Path is not found"
}
}
catch
{
$_.Exception.Message
$_.Exception.ItemName
Write-Error "Set-XMLAttribute function failed."
}
}
End {}
} # End Function Update-XMLAttribute
Set-XMLAttribute -Path "E:\Pshscript\web.Config" -xPath "/configuration/system.serviceModel/behaviors/serviceBehaviors/behavior/serviceMetadata" -attribute "externalMetadataLocation" -valueToFind "http" -ValueToReplace "https"