title: Delete User Profile in Windows using PowerShell
body: <p>I am creating a script which should delete profiles which haven't been used in the last 180 days in Windows systems.</p>
  
  <p>Following is my code.</p>
  
  <pre><code>$profiles = Get-WMIObject -Class Win32_UserProfile | Where {
      (!$_.Special) -and
      ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-1))
  }
  $count = $profiles | Measure-Object | select -ExpandProperty Count
  if ($count -eq 0) {
      Write-Output "No Profiles found for Deletion"
      exit
  }
  Write-Output "Number of profiles : $count"
  $profiledeleted = @()
  $profileerror = @()
  foreach ($profile in $profiles) {
      $profile | Remove-WmiObject
      if ($?) {
          $profiledeleted += $profile.Localpath 
          continue
      } else {
          $profileerror += $profile.Localpath
      }
  }
  if ($profiledeleted.Length -gt 0) {
      Write-Output "Localpath of removed profiles"
      $profiledeleted
  }
  if ($profileerror.Length -gt 0) {
      Write-Output "Error While removing below profiles"
      $profileerror
  }
  </code></pre>
  
  <p>The code should run with the system account but I am getting the following error.</p>
  
  <pre>
  Remove-WmiObject :
  At C:\Users\Admin\GRT-2687_deleteunuseduserprofiles.ps1:22 char:32
  +     $profile | Remove-WmiObject &lt;&lt;&lt;&lt;
      + CategoryInfo          : InvalidOperation: (:) [Remove-WmiObject], COMException
      + FullyQualifiedErrorId : RemoveWMICOMException,Microsoft.PowerShell.Commands.RemoveWmiObject
  </pre>
  
  <p>Edit : It is deleting all the data except the folder C:\Users\Username.</p>