The Ansible win_command module runs a command on a Windows host and returns its output, exit code, and any errors. It does not use a shell, so you must call the executable directly (for example ipconfig.exe, not ipconfig), and it will not expand environment variables or interpret pipes and redirection. To use it, you need a Windows host that Ansible can reach over WinRM or SSH, a user account with permission to run the command, and a playbook that targets that host. The steps below cover the setup, a working playbook, and the checks that catch most failures.

What You'll Need

  • A control node with Ansible installed (Linux, macOS, or Windows with WSL). Ansible itself does not run natively on Windows.
  • One or more Windows hosts with WinRM enabled and reachable on the network, or SSH enabled if you prefer that connection method.
  • A Windows account with local administrator rights, or at least the rights needed for the command you intend to run.
  • The ansible.windows collection installed on the control node. Run ansible-galaxy collection install ansible.windows if it is missing.
  • An inventory file that lists the Windows hosts and the connection variables they need.

Step-by-Step

  1. Confirm the collection is installed. On the control node run ansible-galaxy collection list and look for ansible.windows. If it is absent, install it with ansible-galaxy collection install ansible.windows. The module's full name is ansible.windows.win_command; the short name win_command works only when the collection is available.
  2. Prepare the inventory. Create or edit your inventory file and add the Windows host under a group. Set ansible_connection to winrm (or ssh if you configured OpenSSH on the Windows host), plus ansible_user, ansible_password or ansible_ssh_private_key_file, and ansible_port if you are not using the default. For WinRM over HTTPS, also set ansible_winrm_transport and the certificate options your environment requires. Labels and variable names can differ slightly between Ansible versions, so check the current documentation if a variable is rejected.
  3. Test connectivity before writing the playbook. Run ansible win -i inventory.ini -m ansible.windows.win_ping. A successful response confirms WinRM or SSH, authentication, and Python are working. Fix connection errors here rather than inside a larger playbook.
  4. Create a playbook that calls the module. Use the fully qualified name and pass the command as a single string. A minimal example:
- name: Run a Windows command
  hosts: win
  tasks:
    - name: Get IP configuration
      ansible.windows.win_command: ipconfig.exe /all
      register: result

    - name: Show output
      ansible.builtin.debug:
        var: result.stdout_lines
  1. Run the playbook. Execute ansible-playbook -i inventory.ini playbook.yml. The module returns stdout, stderr, rc, and stdout_lines. Check rc first: zero means success, non-zero means the command failed or returned an error code.
  2. Handle non-zero exit codes deliberately. By default a non-zero rc fails the task. If a command legitimately returns a non-zero code (for example a tool that returns 1 when no results are found), set failed_when to match only the codes you consider failures, or use ignore_errors when you truly want to continue. Avoid ignoring errors broadly; it hides real problems.
  3. Use win_shell only when you need shell features. Pipes, redirection, environment variable expansion, and built-in commands such as dir or echo require ansible.windows.win_shell. win_command is the safer default because it does not invoke a shell and is less exposed to quoting problems.
  4. Pass arguments as a list when quoting is tricky. Instead of one long string, supply a list: ansible.windows.win_command: { argv: ['C:\\Program Files\\Tool\\tool.exe', '/flag', 'value with spaces'] }. This avoids most escaping issues and makes the command easier to read. Use the chdir parameter to set the working directory and creates or removes to make the task idempotent.
  5. Check the result and iterate. Inspect stdout_lines in the debug output. If the command produced no output but returned zero, confirm it actually ran by checking a side effect such as a file or service state. Adjust the command, arguments, or working directory and rerun.

Common Mistakes

  • Using win_command for shell built-ins such as dir, echo, or set. These are not executables; use win_shell instead.
  • Forgetting the .exe extension. win_command does not search PATH the way a shell does, so specify the full path or the executable name with its extension.
  • Expecting environment variables such as %TEMP% to expand. They will not; use win_shell or pass the resolved path.
  • Assuming a zero exit code means the task did what you wanted. Some commands return zero even when they report an error in their output; check stdout when the command's behaviour is unusual.
  • Running commands that require an interactive desktop session. WinRM runs commands in a non-interactive session, so GUI tools and some installers will fail or hang.
  • Ignoring quoting. Paths with spaces and arguments containing special characters need careful quoting or the argv list form.

Tips

  • Prefer win_command over win_shell unless you specifically need shell features; it is more predictable and less prone to injection through quoting.
  • Use register and debug during development to see exactly what the command returned, then remove the debug task once the playbook is stable.
  • Make tasks idempotent with creates or removes so repeated runs do not redo work unnecessarily.
  • Set chdir when a command depends on relative paths; otherwise it runs in the default working directory, which may not be what you expect.
  • Keep credentials out of plain inventory files. Use Ansible Vault or an external secret store for passwords and keys.
  • Test commands manually on the Windows host first. If a command fails outside Ansible, it will fail inside Ansible too.

Troubleshooting

If the playbook cannot connect, start with win_ping. A timeout usually means WinRM is not listening, a firewall is blocking the port, or the host name is wrong. An authentication error points to the username, password, or WinRM transport settings; confirm the account can log on locally and that the WinRM listener is configured for the transport you chose. If win_ping works but win_command fails, check the command itself: run it manually on the host, confirm the executable path, and verify the account has permission to run it. A non-zero rc with empty stderr often means the command wrote its error to standard output; read stdout as well. If the task hangs, the command may be waiting for input or a desktop session; add a timeout or switch to a non-interactive alternative. If output is truncated or missing, check whether the command writes to a file or a log instead of the console. When a change to the inventory or playbook does not take effect, confirm you are running the intended file and that no cached facts are overriding your variables.

Frequently Asked Questions

What is the difference between win_command and win_shell?

win_command runs an executable directly without a shell, so pipes, redirection, and environment variable expansion do not work. win_shell runs the command through a shell, which supports those features but is more sensitive to quoting.

Can I run multiple commands in one win_command task?

Not reliably. win_command expects a single executable and its arguments. To run several commands, use separate tasks or switch to win_shell with a script.

Why does my command work manually but fail in Ansible?

The most common causes are a different working directory, a missing environment variable, a non-interactive session, or an account without the required rights. Set chdir, use full paths, and confirm the account permissions.

How do I capture the output of a win_command task?

Use register to store the result, then read result.stdout or result.stdout_lines in later tasks. The rc field holds the exit code.

Does win_command support check mode?

No. Commands are not simulated in check mode, so the task is skipped unless you explicitly allow it. Use creates or removes to make the task safe to skip when the target state already exists.

Can I use win_command to install software?

Only if the installer runs silently and does not require a desktop session. Many installers need interactive input or a GUI; in that case use a dedicated installer module or a silent-install flag supported by the vendor.