Vaclemor
Vaclemor

Reputation: 55

Add XML Element and Attribute with value

I would like to add <logFile directory="D:\Logs\HTTP\example1" /> to each of the site element if it doesn't have it. I have already created a scrip but it doesn't seem to be recognizing the CreateElement method on a foreach object in the xml file it only has .SetAttribute and SetAttributeNode.

$path = "I:\Projects\applicationHostBackUp.config"

$xpath = "/configuration/system.applicationHost/sites/site"

$selector = Select-Xml -Path $path -XPath $xpath | Select-Object -ExpandProperty Node

foreach($object in $selector) {
    if($object -match $object.logFile) {

    }
}

<configuration>
  <system.applicationHost>
    <sites>
           <site name="AppExample" id="3" serverAutoStart="true">
                <application path="/" applicationPool="exampleApp">
                    <virtualDirectory path="/" physicalPath="F:\Web" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="241" />
                </bindings>
                <logFile directory="D:\Logs\HTTP\exampleApp" />
            </site>
           <site name="AppExample2" id="51" serverAutoStart="true">
                <application path="/" applicationPool="exampleApp2">
                    <virtualDirectory path="/" physicalPath="F:\Web" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="241" />
                </bindings>
            </site>
           <site name="AppExample3" id="521" serverAutoStart="true">
                <application path="/" applicationPool="exampleApp3">
                    <virtualDirectory path="/" physicalPath="F:\Web" />
                </application>
                <bindings>
                    <binding protocol="http" bindingInformation="241" />
                </bindings>
            </site>
    </sites>
  </system.applicationHost>
</configuration>

Upvotes: 0

Views: 149

Answers (1)

Emre
Emre

Reputation: 75

This works:

  1. Find all sites without a logFile element
  2. If the logFile element not exists - create a new one
  3. Create a new attribute Directory and set the value
  4. Add the Directory attribute to the logFile element
  5. Append the logfile element to the the site element

    $dataFilePath = "I:\Projects\applicationHostBackUp.config"
    
    [xml]$data = Get-content -Path $dataFilePath
    
    foreach ($item in $data.configuration.'system.applicationHost'.sites.site){
    
      if(!$item.logFile) {
        $logFileElement = $data.CreateElement("logFile")
        $directoryAttribute = $data.CreateAttribute("directory")      
    
        $directoryAttribute.psbase.value = "D:\Logs\HTTP\$($item.name)"
        $logFileElement.SetAttributeNode($directoryAttribute)
        $item.AppendChild($logFileElement)
      }
    }
    
    $data.Save($dataFilePath) 
    

Upvotes: 1

Related Questions