Often I find I have to query a Windows server via powershell for some information about the server in my Ansible playbooks. And since the Windows shell is not text based the way a linux shell is, I struggled for a while to cleanly translate the Win32 API objects into easy to parse strings, and then to load those strings into structured data for my playbooks to consume.

But now I think I’ve settled on a flexible and repeatable pattern thanks to the ConvertTo-Json powershell commandlet paried with the built in from_json filter.

- name: query for MyWindowsService state
  win_shell: ConvertTo-Json -Compress @(Get-Service -DisplayName 'MyWindowsService')
  register: service_state

- fail:
    msg: "service not found in expected state"
  when: "(item['Status'] == 4 and item['StartType'] != 2) or (item['Status'] == 1 and item['StartType'] != 4)"
  loop: "{{ service_state.stdout | from_json }}"

Note the use of the -Compress flag, this avoids new line issues and is of course fewer bytes over the network.

This pattern gets around all the funky problems that come with powershell object to string output without having to write a custom filter in my Ansible project.