Search code examples
windowspowershellactive-directory

How can I delete all windows user profiles EXCEPT for the ones I specify?


I am trying to remove all user profiles except for certain profiles I specify (administrator, Public, default, DOMAIN\administrator, etc)

I am able to do this successfully and exclude a single user profile, however I am having issues with the correct syntax to exclude multiple user profiles. Here is the code I have found to successfully list all profiles except administrator:

Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -ne 'administrator' }

which I got from here:

https://adamtheautomator.com/powershell-delete-user-profile/

I changed the -eq to a -ne to exclude the administrator profile, but I also want to exclude several other ones.

I think I need something like:

Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -ne 'administrator','Public','default','DOMAIN\administrator' }

however that does not seem to be working and it's only excluding the first name on the list (administrator).

What would be the correct syntax for this command?

Thanks!


Solution

  • Optional: Create an array with the list you want to keep like this:

    $AccountsToKeep = @('administrator','Public','default','DOMAIN\administrator')
    

    Then use this:

    Get-CimInstance -ComputerName computer1,computer2 -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -notin $AccountsToKeep }
    

    Hope this helps.

    If you like this answer, please don't forget to accept it!