简体   繁体   中英

How to delete contents in Recycle Bin using Ansible

I'm running a playbook against a Windows VM to delete the contents of the recycle bin and the task runs successfully signifying that a change has been made. However, when looking on the server itself, the contents of the recycle bin still remain.

There are several ways to delete the contents of the recycle bin. Here are the following methods I've tried:

Different Ansible playbooks used:

- name: Clean recycle bin
  win_shell: |
    $recycleBin = (New-Object -ComObject Shell.Application).NameSpace(0xa)
    $recycleBin.Items() | ForEach-Object -Process { Remove-Item -Path $_.Path -Force -Recurse }

- name: Clean recycle bin
  win_shell: Clear-RecycleBin -Force

- name: Clean recycle bin
  win_command: cmd.exe /k rd /s /q %systemdrive%\$Recycle.Bin

Using the powershell commands, it will delete everything without prompting me to confirm. I would prefer not to run the cmd.exe command, since it only deletes the contents that pertain to the C:\\ drive, unless I specify the drive letter.

All these commands successfully delete the contents of the recycle bin when run on the server itself but when using Ansible, the contents of the recycle bin remain.

So I realized that running the powershell commands only deletes the contents of the recycle bin for that specific user, not all users.

I decided to collect the drive letters using a powershell command since I didn't get all the drive letters using win_disks_facts. Then I would loop through the drive letters and run the cmd.exe command which cleans up the recycle bin for all users.

- name: Get disk drives
  win_shell: |
    $driveinfo = Get-WmiObject -Class Win32_logicaldisk | where {$_.drivetype -eq 3} | select DeviceID
    $driveinfo.DeviceID
- name: Clean recycle bin
  win_command: cmd.exe /k rd /s /q {{ item }}\$Recycle.Bin
  with_items:
    - "{{ disk_drives.stdout_lines }}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM