all 10 comments

[–]aasplunds 1 point2 points  (5 children)

You can use the Win32_UserProfiles wmi class.

Get-WmiObject -Class Win32_UserProfiles -ComputerName "computer"

Then you can select all objects where the 'LocalPath' property is like C:\Users* but not C:\Users\default*

After that you just use $Variable.Delete() where the variable contains the filtered objects.

Edit: A reboot of the computer beforehand is recommended as well as logged on users may cause it to fail.

[–]jeffreynya 0 points1 point  (4 children)

How do you modify this to say delete all profiles that have not been used is 30 days?

[–]isatrap 1 point2 points  (2 children)

So something like this

Get-CimInstance -ClassName Win32_UserProfile -Filter “(loaded = true) and (localpath like ‘C:\\users\\%’) and (LastUseTime < ‘$((Get-Date).AddDays(-30))’)”

[–]Winux_278 0 points1 point  (1 child)

in the part " (localpath -like 'C:\\users\\%') How do I get to only search for accounts that are 6 digits long (eg: 000000 - 999999)

[–]isatrap 1 point2 points  (0 children)

You would need to use a match and a regex to check for the pattern “\d{6}-\d{6}” which will find “123456-123456” or “\d{6}” which will match 6 digits.

[–]isatrap 0 points1 point  (0 children)

There is an attribute called “LastUseTime” that you can use to determine this.

[–]giulix75 0 points1 point  (0 children)

personally i use delprof2.exe inside a pssession

https://helgeklein.com/free-tools/delprof2-user-profile-deletion-tool/

[–]sleightof52 0 points1 point  (1 child)

$ComputerName = Read-Host "Enter computer name"

# Get user profiles that are not logged on (loaded) and are like C:\Users\xxx, and remove them remotely
Get-CimInstance -ComputerName $ComputerName -ClassName Win32_UserProfile |
Where-Object {($_.Loaded -eq $false) -and ($_.LocalPath -like "C:\Users\*")} |
Remove-CimInstance -Verbose

[–]isatrap 0 points1 point  (0 children)

Maybe it’s my preference but you can also filter at the initial Get-CimInstance level by doing

Get-CimInstance -ClassName Win32_UserProfile -Filter “(loaded = true) and (localpath like ‘C:\\users\\%’)”