Search code examples
xmlpowershellselect-xml

I can't get my Powershell script to save multiple change to my xml file


I try to change 2 innertext in my xml file but it will only save one of the changes when I run the save command. I can't figure out to save both innertext back to the xml file.

Is there anybody that can help me ?

Here is my code:

Clear-Host

$Path = "C:\Program Files (x86)\Netcompany\GetOrganized Outlook Add-in 32-bit\Netcompany.Outlook.properties.config"

$XpathAlias = "/configuration/properties/configs/array/item/goAlias"
$XpathBaseUrl = "/configuration/properties/configs/array/item/baseUrl"

$CurrentAlias = Select-Xml -Path $Path -XPath $XpathAlias | Select-Object -ExpandProperty Node
$CurrentBaseUrl = Select-Xml -Path $Path -XPath $XpathBaseUrl | Select-Object -ExpandProperty Node

Write-Host $CurrentAlias.InnerText
Write-Host $CurrentBaseUrl.InnerText

Write-Host "Choose what GO Environment the Plugin should use:"
Write-Host
Write-Host " 0) Abort"
Write-Host " 1) Prod"
Write-Host

$validchoice = $false
while (-not $validchoice) {
    $ChosenEnvironment = (Read-Host "Choose").Trim().ToUpperInvariant();
    if ("0","1","2","3","4" -notcontains $ChosenEnvironment) 
    {
        Write-Host -ForegroundColor Red "Invalid choice"
    } else {
        $validchoice = $true
    }
}

Write-Host

$newsize = $null
switch ($ChosenEnvironment) {
    "0" { Write-Host "Abort." }
    "1" { 
            $CurrentBaseUrl.InnerText = "Prod";
            $CurrentAlias.InnerText = "Prod";
            $CurrentAlias.OwnerDocument.Save($Path);             
            $CurrentBaseUrl.OwnerDocument.Save($Path);                  
            #Write-Host "GO miljø i Outlook plugin er sat til Prod miljøet"  
        }
}

Solution

  • You are loading and saving the xml file twice and for each save, there is only one update, because you have loaded the xml in two separate variables with

    $CurrentAlias = Select-Xml -Path $Path ..
    $CurrentBaseUrl = Select-Xml ..
    

    I would simplify the code somewhat by like this:

    $Path = "C:\Program Files (x86)\Netcompany\GetOrganized Outlook Add-in 32-bit\Netcompany.Outlook.properties.config"
    
    # load the XML file only once
    $xml = [System.Xml.XmlDocument]::new()
    $xml.Load($Path)
    

    Next is where you do the Read-Host and validation of the choice made

    Finally, inside the valid choice option

    # set the new innerText properties (on the one and only xml you have loaded before)
    $xml.SelectSingleNode("/configuration/properties/configs/array/item/goAlias").InnerText = "Prod"
    $xml.SelectSingleNode("/configuration/properties/configs/array/item/baseUrl").InnerText = "Prod"
    # save the xml
    $xml.Save($Path)