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

Kelly GarciaSenior Systems AdministratorAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kanti PrasadCommented:
Mauro CazabonnetSenior .NET Software EngineerCommented:
$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

Kelly GarciaSenior Systems AdministratorAuthor Commented:
how do I do this for all users instead of the one user?

thank you soo much!
Webinar: Cyber Crime Becomes Big Business

The rising threat of malware-as-a-service is not one to be overlooked. Malware-as-a-service is growing and easily purchased from a full-service cyber-criminal store in a “Virus Depot” fashion. Join us in our upcoming webinar as we discuss how to best defend against these attacks!

Mauro CazabonnetSenior .NET Software EngineerCommented:
$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 
             { 
                 $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 $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 $username from $Server - Error $($_.Exception.Message)"
              }
        }
}

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Kelly GarciaSenior Systems AdministratorAuthor Commented:
HI,

THank you for the wonderful script, however it fails at

$profileFolder = Get-Item $userProfile.LocalPath


please help!
Kelly GarciaSenior Systems AdministratorAuthor Commented:
it says it deleted the profile but when i check its still there??
Kelly GarciaSenior Systems AdministratorAuthor Commented:
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?
Mauro CazabonnetSenior .NET Software EngineerCommented:
I'll review and update shortly
M
Mauro CazabonnetSenior .NET Software EngineerCommented:
LastAccessTime is the way to go
Kelly GarciaSenior Systems AdministratorAuthor Commented:
thank you, its a fantastic script!
Kelly GarciaSenior Systems AdministratorAuthor Commented:
will this delete the publilc and the default folders also?
Kelly GarciaSenior Systems AdministratorAuthor Commented:
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."
Mauro CazabonnetSenior .NET Software EngineerCommented:
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

Mauro CazabonnetSenior .NET Software EngineerCommented:
I changed the coding for binding to remote machines
Kelly GarciaSenior Systems AdministratorAuthor Commented:
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?
Mauro CazabonnetSenior .NET Software EngineerCommented:
I'll post code with exclusion support
Mauro CazabonnetSenior .NET Software EngineerCommented:
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

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.