Remove user with filter based on SID

628 Views Asked by At

I have some machines with a lot of profiles and would like to remove all of them, except for 3, that are admins.

this would do the job if i wanted to remove everything

Get-WMIObject -Class Win32_USerProfile -ComputerName $computer | Remove-WmiObject

I have tried to do it with the where clause and -filter, but wasnt successfull.

Here are some examples

Get-WMIObject -Class Win32_UserProfile -ComputerName $computer | where {($.SID -neq $UserSID)} | Remove-WMIObject

...

Get-WMIObject -Class Win32_USerProfile -ComputerName $computer -Filter "SID = TEST" | Remove-WmiObject

EDIT: I almost got it like this:

 Get-WMIObject -Class Win32_USerProfile -ComputerName $computer | Where-Object -FilterScript {$_.SID -ne "S-1-5-18" -and $_.SID -ne "S-1-5-19" -and $_.SID -ne "S-1-5-20"} |Remove-WmiObject -WhatIf

This way i can filter the output but i got an exception

+ CategoryInfo          : NotSpecified: (:) [Remove-WmiObject], ArgumentException
1

There are 1 best solutions below

3
On
$UserSID = 'S-1-5-18'
Get-WMIObject -Class Win32_UserProfile -ComputerName $computer | where {$_.SID -ne $UserSID} | Remove-WmiObject -WhatIf
Get-WMIObject -Class Win32_USerProfile -ComputerName $computer -Filter "SID != '$UserSID'" | Remove-WmiObject -WhatIf