0

How to implement output the existing value from XML file and changed value? I'm using this code for changing configuration in xml files:

[xml]$config = gc $DirectoryPath\Web.config
$config.configuration.appSettings.Item(0).value = "new-value1"
$config.configuration.appSettings.Item(1).value = "new-value2"     
$config.Save("$DirectoryPath\Web.config")

I need to get the output of both values (existing and changed). If I use brackets:

(Write-Host($config.configuration.appSettings.Item(0).value) = "new-value1")

I'm geting needed output result:

value1 = new-value1

but the changes in the XML file are not applied.

And also it will be great if I get the existing line number from XML file in output, something like:

value1 = new-value1 at line #10

1 Answer 1

1

You cannot output an XML element and assign a new value to it at the same time. Use two statements:

Write-Host $config.configuration.appSettings.Item(0).value
$config.configuration.appSettings.Item(0).value = "new-value1"

Add another Write-Host statement after assigning the new value if you want to output both values.

You can shorten the statements a little by assigning a parent object to a variable first:

$appSettings = $config.configuration.appSettings
Write-Host $appSettings.Item(0).value  # output old value
$appSettings.Item(0).value = "new-value1"
Write-Host $appSettings.Item(0).value  # output new value

If you're trying to get old and new value in the same output line you could do something like this:

$appSettings = $config.configuration.appSettings
Write-Host -NoNewline $appSettings.Item(0).value  # output old value
$appSettings.Item(0).value = "new-value1"
Write-Host " =" $appSettings.Item(0).value        # output new value

Or assign the value to another variable first before changing it, and then output both values afterwards:

$appSettings = $config.configuration.appSettings
$oldvalue = $appSettings.Item(0).value
$appSettings.Item(0).value = "new-value1"
Write-Host ('{0} = {1}' -f $oldvalue, $appSettings.Item(0).value)

As for getting line numbers, XML is not a line-oriented format, so that won't work.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.