none
Delete User Profile in Windows using Powershell RRS feed

  • Question

  • I am Creating a script wich should delete profiles which is unused from last 180 days in windows system.

    Following is my code.

        $profiles = Get-WMIObject -class Win32_UserProfile | Where {(!$_.Special) -and ($_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-180))}

    foreach($profile in $profiles)
        {
            $profile | Remove-WmiObject
    }

    How ever it is deleting all the profile data except the parent folder C:\Users\Username ,with below exception.

    Remove-WmiObject : At C:\Users\Admin\GRT-2687_deleteunuseduserprofiles.ps1:22 char:32 + $profile | Remove-WmiObject <<<< + CategoryInfo : InvalidOperation: (:) [Remove-WmiObject], COMExc eption + FullyQualifiedErrorId : RemoveWMICOMException,Microsoft.PowerShell.Comma
    nds.RemoveWmiObject

    • Moved by Bill_Stewart Friday, March 15, 2019 6:28 PM This is not "fix/debug/rewrite my script for me" forum
    Friday, January 25, 2019 12:11 PM

All replies

  • $profile.Delete()

    This removes the profile and cleans the registry correctly.  Removing the instance will not work correctly.


    \_(ツ)_/

    Friday, January 25, 2019 4:56 PM
  • Get-WMIObject -class Win32_UserProfile -Filter 'Special=False'| 
        Where-Object {$_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-180) } |
        ForEach-Object{ $_.Delete()}
    


    \_(ツ)_/

    Friday, January 25, 2019 4:58 PM