Link to home
Start Free TrialLog in
Avatar of Kelly Garcia
Kelly GarciaFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Delete Profiles older than 14 days Script

Hi Guys,

I have written a script to delete profiles from machines and servers, however this is for users, I need help to write a script that will delete profiles that is older than 30 days with some exceptions, please can someone help me edit the script I have already written, thank you in advance:

$users=@("c.horsfield")

$PServers=@("CI-RDS01","CI-RDS02","CI-RDS03")

foreach ($server in $PServers)

{





        foreach ($user in $users)

               
               {

               try 
                       { 


                       (Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like "c:\users\$user"}).Delete()      
                       

                               Write-Host "$user deleted successfully on $server" 
                       }
                       
                       
               catch

                       {

                               Write-Host "Error For $username from $Server - Error $($_.Exception.Message)"


                       }

               }


}

Open in new window

Avatar of Kanti Prasad
Kanti Prasad

Avatar of Mauro Cazabonnet
$users=@("c.horsfield")

$PServers=@("CI-RDS01","CI-RDS02","CI-RDS03")

$currentDate=(GET-DATE)

foreach ($server in $PServers)
{
    foreach ($user in $users)
        {
             try 
             { 
                 $userProfile = New-Object System.Object
                 $userProfile = Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like "c:\users\$user"}
                 $profileFolder = Get-Item $userProfile.LocalPath
                 $profileDate = $profileFolder.CreationTime
                 $datediff = NEW-TIMESPAN –Start $profileDate –End $currentDate
       
                 if ($datediff.days -gt 30)
                 {
                  (Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like $userProfile.LocalPath}).Delete()      
                   Write-Host "$user deleted successfully on $server" 
                 }
              }
              catch
              {
                  Write-Host "Error For $user from $server - Error $($_.Exception.Message)"
              }
        }
}

Open in new window

Avatar of Kelly Garcia

ASKER

how do I do this for all users instead of the one user?

thank you soo much!
ASKER CERTIFIED SOLUTION
Avatar of Mauro Cazabonnet
Mauro Cazabonnet
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
HI,

THank you for the wonderful script, however it fails at

$profileFolder = Get-Item $userProfile.LocalPath


please help!
it says it deleted the profile but when i check its still there??
i want to do it by

LastAccessTime
LastAccessTimeUtc
LastWriteTime
LastWriteTimeUtc

instead of creationtime, that way I would only be deleting the profiles that are not used. which is the best to use out of hte four?
I'll review and update shortly
M
LastAccessTime is the way to go
thank you, its a fantastic script!
will this delete the publilc and the default folders also?
I get these error messsages when attempting on a remote machine:

Error For  from c10068 - Error Cannot bind parameter 'Start' to the target. Exception setting "Start": "Object reference
 not set to an instance of an object."
It will try to remove everything under C:\Users
We can have exclusions if need

$PServers=@("CI-RDS01","CI-RDS02","CI-RDS03")
$currentDate=(GET-DATE)

foreach ($server in $PServers)
{
    $RootPath = "\\$server\c$\Users"
    If ($RootPath -ne $null)
    {
        $Folders = dir $RootPath | where {$_.psiscontainer -eq $true} 
    }
    
    foreach ($user in $Folders)
    {
        try 
        { 
            $profilePath = $RootPath + "\" + $user
            $profileFolder = Get-Item $profilePath
            $profileDate = $profileFolder.LastAccessTime
            $datediff = NEW-TIMESPAN –Start $profileDate.Date –End $currentDate
                                            
            if ($datediff.days -gt 30)
            {
                if (Test-Path $profilePath)
			    {
				    $command = "& cmd.exe /c rmdir /S /Q '$profilePath' 2>&1"
                    $console_output_array = Invoke-Expression $command
			    }
                if ($console_output_array -ne $null)
			    {
				    $console_output_string = [string]::join("`r",$console_output_array)
				    foreach ($error in $console_output_string)
				    {          
                        Throw $error
					}	
				}
                else { Write-Host "$profilePath deleted successfully on $server" }
            }
        }  
        catch
        {
            Write-Host "Error For $profilePath from $Server - Error $($_.Exception.Message)"
        }
    }
}

Open in new window

I changed the coding for binding to remote machines
i've did it this way, and it worked on the remote machine

$PServers=@("c10068")

$currentDate=(GET-DATE)

foreach ($server in $PServers)
{
    $RootPath = "\\$server\c$\Users"
    If ($RootPath -ne $null)
    {
        $Folders = dir $RootPath | where {$_.psiscontainer -eq $true} 
    }
    
    foreach ($user in $Folders)
        {
             try 
             { 
                 $userProfile = New-Object System.Object
                 $userProfile = Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like "c:\users\$user"}
                 if ($userProfile.LocalPath -ne $null)
                 {
                    $profileFolder = Get-Item \\$server\c$\users\$user
                    $profileDate = $profileFolder.LastAccessTime
                    $datediff = NEW-TIMESPAN –Start $profileDate –End $currentDate
       
                    if ($datediff.days -gt 14)
                    {
                        (Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like $userProfile.LocalPath}).Delete()      
                        Write-Host "$user deleted successfully on $server" 
                    }
                 }
              }
              catch
              {
                  Write-Host "Error For $username from $Server - Error $($_.Exception.Message)"
              }
        }
}

Open in new window


i want to add exceptions to the script, for example there is a folder profile called defaultapppool and i do not want this deleted. how do i do this?
I'll post code with exclusion support
Added exclusion code, you can update the exclusion array as needed

$PServers=@("c10068")
$currentDate=(GET-DATE)
$ExcludeProfiles = "Profile1","defaultapppool","Profile2"

#Hash Tables
    $HashExcludeProfiles = $null
#endregion

#Populate BaseProfiles Hash Table

function ProfileExclusions
{
	$script:HashExcludeProfiles = @{}
	foreach ($profile in $ExcludeProfiles)
	{
		if (!($script:HashExcludeProfiles.ContainsKey($profile)))
		{
			$script:HashExcludeProfiles.Add($profile,1)
		}
	}
}

function RemoveProfiles
{
    foreach ($server in $PServers)
    {
        $RootPath = "\\$server\c$\Users"
        If ($RootPath -ne $null)
        {
            $Folders = dir $RootPath | where {$_.psiscontainer -eq $true} 
        }
    
        foreach ($user in $Folders)
        {
            try 
            { 
                $currprofile = $user.Name.trim()
                if (!($script:HashExcludeProfiles.ContainsKey($currprofile)))
                {
                    $userProfile = New-Object System.Object
                    $userProfile = Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like "c:\users\$user"}
                    if ($userProfile.LocalPath -ne $null)
                    {
                        $profileFolder = Get-Item \\$server\c$\users\$user
                        $profileDate = $profileFolder.LastAccessTime
                        $datediff = NEW-TIMESPAN –Start $profileDate –End $currentDate
       
                        if ($datediff.days -gt 14)
                        {
                            #(Get-WmiObject Win32_UserProfile -Computername $server | Where {$_.LocalPath -like $userProfile.LocalPath}).Delete()      
                            Write-Host "$user deleted successfully on $server" 
                        }
                    }
                }
            }
            catch
            {
                Write-Host "Error For $username from $Server - Error $($_.Exception.Message)"
            }
        }
    }
}

#Call functions
ProfileExclusions
RemoveProfiles

Open in new window