0

I try to change an element text, using ansible.windows.win_shell.

This is the XML I have:

<element-A>
    <element-B />
</element-A>

and this is the XML I would like to have:

<element-A>
    <element-B> TEXT </element-B>
</element-A>

The win_shell I tried to run:

- name: some-name
  win_shell: |
    [xml]$myFile = Get-Content "C:\MyFile.xml"
    $myFile.element-A.element-B = 'TEXT'
    $myFile.Save("C:\MyFile.xml")

The error I get:

"The property 'element-B' cannot be found on this object. Verify that the property exists and can be set."

Can someone help?

toffee
  • 47
  • 2
  • 3
  • 9
  • have you tried the [lineinfile](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/lineinfile_module.html) Ansible module? another option is to [template](https://docs.ansible.com/ansible/latest/collections/ansible/builtin/template_module.html) the XML file; Ansible modules will take care of idempotency, so, if the playbooks need to be re-executed, the resulting file will be always the same; with the `win_shell` module that code segment will be added every time the playbook is executed – Carlos Monroy Nieblas Feb 19 '23 at 18:51

2 Answers2

0

As you know win_shell calls powershell by default. And if you want to call a method with special characters in powershell, you should quote the method call like this:

$myFile.'element-A'.'element-B' = 'TEXT'

this should work.

Oliver Gaida
  • 1,722
  • 7
  • 14
0

Using SelectSingleNode solved the problem for me:

   - name: some-name
      win_shell: |
        [xml]$myFile = Get-Content "C:\MyFile.xml"
        $myFile.SelectSingleNode("//element-A/element-B").InnerText = "TEXT"
        $myFile.Save("C:\MyFile.xml")
toffee
  • 47
  • 2
  • 3
  • 9