Here's my powershell script to delete ALL user accounts that don't match the current user account you're logged into along with the "Administrator" and "Guest" account. This will output to
del_users.txt a list, line by line of the user names it has attempted to delete, and don't match the current $user and "Administrator" and "Guest"
Code:
$Comp = "."
$UsrAccounts = get-wmiobject -class "Win32_UserAccount" -namespace "root\CIMV2" `
-filter "LocalAccount = True" -computername $Comp
write-host > del_users.txt
foreach ($objItm in $UsrAccounts) {
if ($objItm.Name -ne $env:username `
-and $objItm.Name -ne "Administrator" `
-and $objItm.Name -ne "Guest") {
$objItm.Name >> del_users.txt
}
}
$del_array = get-content del_users.txt | %{ $_ }
foreach ($str in $del_array) {
net users $str /del
}
What i'm doing here is taking data from the WMIObject class "Win32_UserAccount" and returning values ONLY for the User strings. If they don't match my current user account name, and "Administrator" and "Guest" then it adds it to a text file called "del_users.txt" on a new line.
Then after that loops through, we create a hash array getting the full string of the content in that created file, and add each line as a string item to the hash array defined as $del_array. Now we look at each object/string value in that array and apply the net users /del command line method to that specific username. Therefore removing all the useless user accounts except for the main ones that should be on your machine.