Ansible: How to run PowerShell script on Windows Server

This post shows how to run PowerShell script on Windows Server target with Ansible.
There are three manners:

Idempotency depends on a script.

Run a script written in a Playbook

You can write a PowerShell script in a playbook directly and run on Windows Server target like the following figure.

Use win_shell module like the following.

---
- name: Test Playbook
  hosts: 192.168.1.1

  tasks:
  - name: Run shell
    win_shell: |
      $ret = Test-Path -Path C:\tmp
      if ($ret) {
        Remove-Item -Path C:\tmp -Force
      }

win_shell module runs written script on PowerShell on Windows Server target.
It is useful if script consists of a few lines. However, if not, write script as a ps1 file and follow the next manners.

Run ps1 file that is on Ansible Controller

The script (test.ps1) to be run is on the Ansible Controller. You can run it on PowerShell on Windows Server target like the following figure.

Ansible exec script 2

Note: Assume that the script to be run is ./scripts/test.ps1
Use script module like the following.

---
- name: Test Playbook
  hosts: 192.168.1.1

  tasks:
  - name: Run ps1
    script: ./scripts/test.ps1

Run ps1 file that is on Target

The script (test.ps1) to be run is on Windows Server target. You can run it on PowerShell on Windows Server target like the following figure.

Note: Assume that the script to be run is C:\test.ps1
Use win_shell module like the following.

---
- name: Test Playbook
  hosts: 192.168.1.1

  tasks:
  - name: Run ps1
    win_shell: C:\\test.ps1

\ of file path need to be written \\.

That’s about it.