0

I’m relatively new to PowerShell and I'm having issues creating a script to modify and save an XML file (web.config) using PowerShell. The Structure of the XML file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
       <add key="Password" value="Test1234" />
  </appSettings>
</configuration>

I have tried numerous approaches on trying to get powershell to edit the Password Value and save it again but non are working. My latest being:

$webConfig = "Z:\TEMP\Web.config"
$doc = new-object System.Xml.XmlDocument
$doc.Load($webConfig)
$doc.get_DocumentElement()."appSettings".WebAdminPassword.value = "$Password"
$doc.Save($webConfig)

the variable $Password is a Random 15 character password being generate earlier in the script. Can anyone advise where im going wrong? Thanks!

1 Answer 1

1

Try this:

$xml = [xml]@'
 <?xml version="1.0" encoding="utf-8"?>
 <configuration>
   <appSettings>
        <add key="Password" value="Test1234" />
   </appSettings>
 </configuration>
 '@

$xml.configuration.appSettings.add | Where {$_.Key -eq 'password'} |
                                     Foreach {$_.value = 'newpassword'}
$xml.Save()

As far as I can see, there is no element or attribute named WebAdminPassword.

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

1 Comment

Excellent Thank you so much you resolved my issue! There was no attribute WebAdminPassword this was from the the other file i was trying to edit. Thankyou for help

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.