title: Deleting user profiles in PowerShell occasionally leaves behind profiles
body: <p>I have created my first PowerShell script to mass delete user profiles, For the most part it works fine, however, it does occasionally leave behind some profiles that cannot be found in Powershell when <code>Get-CimInstance win32_UserProfile</code> is run.</p>
  
  <p>Even though PowerShell seemingly does not see these profiles they do get touched by the script so that their last accessed date is current, everything aside from their appdata folders are deleted, and they are still in the <code>C:\Users</code> directory.</p>
  
  <p>The only solution I have currently is to manually select these profiles within <code>Users</code> and then delete them but I'm trying to completely automate this process. I am at a loss as to what could cause this, so any advice or guidance is greatly appreciated. Here is my code: </p>
  
  <pre><code># Grab all the user profiles and ignore anything in our exceptions
  $Profiles = Get-CimInstance Win32_UserProfile | where {((!$_.Special) -and ($_.LocalPath -ne "C:\Users\Administrator") -and ($_.LocalPath -ne "C:\Users\admin1") -and ($_.LocalPath -ne "C:\Users\admin2") -and ($_.LocalPath -ne "C:\Users\admin3") -and ($_.LocalPath -ne "C:\Users\admin4"))}
  
  # Get the number of profiles to use in -PercentComplete
  $ProfilesCount = $Profiles.Count 
  
  # This for loop iterates through profiles and deletes them as well as creates our progress bar
  Function ProfilesB-Gone 
  {
      for ($i = 1; $i -lt $ProfilesCount; $i++)
      { 
          # Our progress bar is generated and updated 
          Write-Progress -Activity 'Removing Profiles' -Status "Deleted $i out of $ProfilesCount profiles" -PercentComplete (($i/$ProfilesCount) * 100) 
  
          # Here we're suppressing errors and continuing while deleting our profiles 
          Remove-CimInstance $Profiles[$i] -EV Err -EA SilentlyContinue 
      }
      # Remove progress bar once complete
      Write-Progress -Activity 'Removing Profiles' -Status 'Complete!' -Completed
  }
  
  # Call function
  ProfilesB-Gone;
  
  # Remove all leftover profiles that remain ocasionally due to noncritical and inconsistent bug and suppress errors. Not suppressing errors causes as many error windows to show as there were $ProfilesCount.
  $Profiles | Remove-CimInstance -EV Err -EA SilentlyContinue 
  
  # Give success message to inform user of script completion
  Write-Host "Profiles Deleted!"
  </code></pre>