Playbook - Clearing Users' Data Files in a Group of Windows Machines

The playbook below will remove all users' data in a computer that belongs in an inventory group. Below is a list of steps that this playbook will do:

  1. Disable and remove the target user
  2. Reboot to remove any file locks from the logged in user
  3. Remove any files in the user's directory, skipping symbolic links
  4. Re-create a public user with the same username and empty password that cannot be changed
  5. Enable auto login for the user so that new machine will be configured for auto login as well
  6. Reboot computer to enable the configuration

The playbook is as follows, please change the variables encapsulated in < > with the desired values:

---
- hosts: <inventory group / host>
  tasks:
  - name: remove user account
    win_user:
      name: <username>
      account_disabled: yes
      state: absent
  - name: reboot
    win_reboot:
      msg: "Scheduled reset started, windows will reboot in 90 seconds"
      pre_boot_delay: 90
  - name: remove any files in the folder tree
    ignore_errors: yes
    win_shell: |
      $Path = "C:\Users\<username>"
      Remove-Item "$Path" -Force -Recurse -ErrorAction SilentlyContinue
      if (Test-Path "$Path" -ErrorAction SilentlyContinue)
      {
          $folders = Get-ChildItem -Path $Path -Directory -Force -ErrorAction SilentlyContinue
          ForEach ($folder in $folders)
          {
              Remove-Tree $folder.FullName -Force -ErrorAction SilentlyContinue
          }

          $files = Get-ChildItem -Path $Path -File -Force
          ForEach ($file in $files)
          {
              Remove-Item $file.FullName -Force -ErrorAction SilentlyContinue
          }

          if (Test-Path "$Path" -ErrorAction SilentlyContinue)
          {
              Remove-Item $Path -Force -ErrorAction SilentlyContinue
          }
      }
  - name: re-add user account
    win_user:
      name: <username>
      state: present
      groups: Users
      user_cannot_change_password: yes
      password_expired: no
      password_never_expire: yes
  - name: enable auto logon
    win_shell: |
      Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'AutoAdminLogon' -Value '1'
      Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'DefaultUsername' -Value '<default username>'
      Set-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' -Name 'DefaultPassword' -Value ''
  - name: reboot to apply new settings
    win_reboot:
      msg: "Scheduled reset completed, windows will reboot in 5 seconds"
      pre_boot_delay: 5

References: