Script to remove profiles for terminated users from workstations

Tom Bingeman 21 Reputation points
2021-02-05T01:49:47.533+00:00

I am trying to write this script to remove the user profiles of people that have left our company from the workstations. I am doing this to conserve disk space as these people have not been with the company for more than 90 days. Any help you can provide would be great.

$Computers = Get-Content "C:\Temp\computers.txt"
$users = Get-Content "C:\Temp\users.txt"

foreach($computer in $computers){
    foreach($user in $users){ Invoke-Command -ComputerName $computer -ScriptBlock {
        param($user)
        $localpath = 'c:\users\' + $user
        Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq $localpath} | 
        write-output "Removing profile $localpath" | Remove-WmiObject}
    }
}
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,576 questions
0 comments No comments
{count} votes

Accepted answer
  1. Ian Xue 38,466 Reputation points Microsoft Vendor
    2021-02-05T07:02:30.483+00:00

    Hi,

    You can use $using:user to identify the local variable $user
    About Remote Variables

    foreach($computer in $computers){  
        foreach($user in $users){ Invoke-Command -ComputerName $computer -ScriptBlock {  
            $localpath = 'c:\users\' + $using:user  
            write-output "Removing profile $localpath"   
            Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq $localpath} | Remove-WmiObject     
            }  
        }  
    }  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Tom Bingeman 21 Reputation points
    2021-02-05T15:01:55.523+00:00

    Thank you very much for your help. My script is now working as intended.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.