Quote mismatch when executing a command on windows boxes

Hello,

I have several windows boxes with directories on them full of log files. I want to delete all log files older then 7 days. The dos command that does it is

forfiles /d -7 /c “cmd /c del @path

I tested the command on some of the windows boxes and it works correctly. Next I tried to use it an ansible playbook:

  • name: clean test logs

win_command: forfiles /d -7 /c “cmd /c del @path
args:
chdir: “{{ logs_backup_dir }}”

I got the following error

FAILED! => {“changed”: true, “cmd”: “forfiles /d -7 /c "cmd /c del @path"”, “delta”: “0:00:00.053005”, “end”: “2017-07-28 05:59:27.397115”, “failed”: true, “rc”: 1, “start”: “2017-07-28 05:59:27.344110”, “stderr”: “ERROR: Invalid syntax. ‘/c’ option is not allowed more than ‘1’ time(s).\r\nType "FORFILES /?" for usage.\r\n”, “stdout”: “”, “stdout_lines”: , “warnings”: }

It looks like it confuses the option /c of forfiles command with the option /c of cmd command.

I tried various quote combinations with no luck

win_command: “forfiles /d -7 /c "cmd /c del @path"”
win_command: “forfiles /d -7 /c ‘cmd /c del @path’”

and so on…

Any idea how can I provide the quotes so that the commands are grouped together?

Thank you in advance.

Regards
rambius

I’d probably try and solve this one a different way.

If recording the files that you’ve removed is important, I’d probably use win_find http://docs.ansible.com/ansible/latest/win_find_module.html then register the results and then use the registered results as with_items input to win_file state=absent

If you are really just tidying up you can probably do this using a powershell 1 liner. Its not as pretty as the dos cmd version (not NOT tested, so make sure you are happy with it before running it for real).

win_shell: Get-ChildItem -Path . -Recurse -Force | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force
args:
   chdir: "{{ logs_backup_dir }}"