Share via

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 for business | Windows Server | User experience | PowerShell
0 comments No comments

Answer accepted by question author

Anonymous
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.

Was this answer helpful?

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.

    Was this answer helpful?

    0 comments No comments

Your answer

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