Ansible can execute PowerShell commands on Windows targets via the win_shell and win_powershell modules, enabling remote automation of Windows systems. This works by using WinRM (Windows Remote Management) to connect securely to Windows hosts, allowing you to run scripts, cmdlets, or one-liners just as you would locally—but from a Linux or Windows Ansible control machine. You need Ansible installed, WinRM properly configured on target Windows machines, and appropriate permissions (typically Administrator-level access on the remote host).

What You'll Need

  • An Ansible control machine (Linux, macOS, or Windows with Ansible installed)
  • Ansible version 2.8 or higher (earlier versions have limited Windows support)
  • One or more Windows target hosts running Windows 7 SP1, Windows Server 2008 R2 SP1, or newer
  • PowerShell 3.0 or higher on target Windows hosts (standard on all modern Windows versions)
  • WinRM service enabled and configured on target Windows machines
  • Network connectivity between control and target hosts (port 5985 for HTTP or 5986 for HTTPS)
  • Valid credentials with local Administrator rights on target Windows systems

Step-by-Step

  1. Install Ansible on your control machine: On Linux (Debian/Ubuntu), run sudo apt update && sudo apt install ansible. On macOS, use brew install ansible. On Windows, install via pip install ansible in PowerShell (ensure Python 3.6+ is installed first). Verify with ansible --version.
  2. Enable WinRM on target Windows hosts: Open PowerShell as Administrator on each Windows machine. Run the following to configure WinRM: Enable-PSRemoting -Force. This starts the WinRM service, sets it to auto-start, and creates a firewall rule for HTTP on port 5985. For HTTPS (recommended for production), run winrm quickconfig -q followed by winrm quickconfig -transport:https (requires a valid SSL certificate).
  3. Test WinRM connectivity locally: On the target Windows host, run winrm enumerate winrm/config/listener to confirm listeners exist. Then test from another machine using Test-WsMan <target_IP_or_hostname>. If successful, you’ll see WS-Management service details.
  4. Configure Ansible inventory for Windows: Edit or create your inventory file (e.g., /etc/ansible/hosts or a custom file like windows.ini). Add your Windows host with WinRM-specific variables. Example: [windows]winserver1 ansible_host=192.168.1.50 ansible_connection=winrm ansible_port=5985 ansible_winrm_server_cert_validation=ignore ansible_user=Administrator ansible_password='P@ssw0rd123!' Note: Store credentials securely (see Tips section).
  5. Run a basic PowerShell command with win_shell: Use the win_shell module for simple commands. In your terminal, run: ansible windows -i ./windows.ini -m win_shell -a "Get-Process | Where-Object { $_.CPU -gt 100 }" This lists processes consuming over 100 seconds of CPU time on all hosts in the windows group.
  6. Use win_powershell for script blocks : For multi-line or complex scripts, use win_powershell . Create a playbook file (e.g., check_disk.yml ): --- name: Check disk space on Windows hosts hosts: windows gather_facts: no tasks: - name: Get disk info win_powershell: script: | Run it with ansible-playbook check_disk.yml .
  7. Pass arguments safely: Avoid embedding variables directly in scripts. Use args in win_powershell for clean parameterization: win_powershell: script: | param([string]$Path, [int]$MinSize) Get-ChildItem $Path -Recurse | Where-Object { $_.Length -gt $MinSize } | Select-Object FullName, Length args: Path: "C:\Logs" MinSize: 10485760

Common Mistakes

  • Skipping WinRM configuration: Ansible fails with "HTTP status 401" (unauthorized) or "connection refused" if WinRM isn’t running or listeners aren’t set up. Always run Enable-PSRemoting first.
  • Using HTTP in environments requiring HTTPS: Many orgs block non-encrypted WinRM traffic. If servers require HTTPS, set ansible_winrm_transport: ssl and ansible_port=5986.
  • Hardcoding passwords in inventory: This is a security risk. Use Ansible Vault (ansible-vault encrypt_string) or Windows Credential Manager with ansible_winrm_operation_timeout_sec and ansible_winrm_read_timeout_sec tuned for long-running commands.
  • Ignoring PowerShell execution policy: Default Restricted blocks scripts. Ansible’s win_shell bypasses this, but for win_powershell, ensure Set-ExecutionPolicy RemoteSigned is applied on targets (via GPO or manual setup).
  • Using wrong module: shell and command modules don’t work on Windows. Always use win_shell or win_powershell.

Tips

  • Use gather_facts: no in playbooks to skip fact collection on Windows (it’s slow and error-prone without ansible_windows_facts).
  • For large-scale deployments, configure WinRM with certificate-based auth: generate a self-signed cert, bind it to the listener, and pass ansible_winrm_cert_pem and ansible_winrm_cert_key_pem in inventory.
  • Debug slow commands by increasing timeouts: Add -e "ansible_winrm_operation_timeout_sec=120 ansible_winrm_read_timeout_sec=130" to your command.
  • Pre-test PowerShell commands manually on a target machine first—especially those using .NET or COM objects—to ensure they work outside Ansible.
  • Group Windows hosts by OS version or function in your inventory for targeted runs (e.g., [win2019:children]).
  • Use the become keyword only when necessary; win_shell runs as the specified user by default, but become: yes can cause issues with credential delegation.

Troubleshooting

If your PowerShell command fails, follow this checklist:

  1. Check basic connectivity: From your Ansible control machine, run Test-NetConnection <target> -Port 5985 (PowerShell) or telnet <target> 5985 (if telnet client is installed). If it fails, verify network firewalls and WinRM service status on the target.
  2. Verify WinRM configuration: On the target, run winrm get winrm/config and confirm Client and Service sections allow remote management. Look for AllowUnencrypted = true if using HTTP.
  3. Test credentials manually: Use Enter-PSSession -ComputerName <target> -Credential <user> to log in interactively. If this fails, Ansible will too.
  4. Enable verbose Ansible output: Add -vvv to your command (e.g., ansible windows -m win_shell -a "whoami" -vvv) to see raw WinRM errors, including HTTP status codes and response bodies.
  5. Handle SSL certificate errors: If using HTTPS with self-signed certs, add ansible_winrm_server_cert_validation=ignore to inventory (not recommended for production). Better: install a trusted cert on the target.
  6. Address timeout issues: Commands taking >30 seconds often fail by default. Increase timeouts globally in /etc/ansible/ansible.cfg with winrm_operation_timeout_sec = 120 and winrm_read_timeout_sec = 130.
  7. Check PowerShell version: Run $PSVersionTable.PSVersion on the target. If below 3.0, update PowerShell (requires .NET Framework 4.5+).

Frequently Asked Questions

Can I run PowerShell scripts stored on the control machine against Windows targets?

Yes. Use win_powershell with the script parameter set to the local file path (e.g., script: "C:\scripts\check_disk.ps1"), or use win_copy to transfer the script first, then execute it remotely.

Do I need PowerShell Core or is Windows PowerShell fine?

Windows PowerShell (5.1+) is fully supported. PowerShell Core (6+) works too, but Ansible’s win_ modules target Windows PowerShell by default. To use PowerShell Core, specify the path explicitly in win_powershell via executable: "pwsh.exe".

How do I pass sensitive variables like passwords securely?

Never hardcode them. Use ansible-vault to encrypt the password in your inventory file, or store credentials in Windows Credential Manager and reference them with ansible_winrm_password set to a vault-encrypted variable.

Can I run Ansible from a Windows control machine?

Yes. Install Ansible via pip on Windows, but ensure the pywinrm Python package is installed (pip install pywinrm). Some older Windows versions require additional Visual C++ Redistributables for WinRM dependencies.

Why does my win_shell command return "The term 'xyz' is not recognized"?

This usually means the command (e.g., a custom cmdlet or script) isn’t in the PowerShell session’s path. Either import the module first (e.g., Import-Module MyModule), or use the full path to the executable. win_shell runs with a minimal environment.

Is Ansible’s Windows support production-ready?

Yes. Ansible has full Windows support since 2015, with enterprise adoption in large organizations. Always test your playbooks in a non-production environment first, and use check_mode: yes to validate changes before applying them.