Deleting users in C drive and registry using PowerShell ISE

69 Views Asked by At

Code is not actually deleting users from the drive/reg

I did a little research and found some base code that I modified to apply to my situation at my job. Old users are a constant issue that I have to constantly fix since they fill up the C drive and cause outlook/teams to not work because of a lack of disk space.

Get-CimInstance win32_userprofile -verbose | 
    Where {$_.LastUseTime -lt $(Get-Date).Date.AddDays(-x) } | 
    Remove-CimInstance -Verbose

Running this in theory should delete all users older than X days from the c drive and reg key according to my research. And when I run the command in ISE with admin privs, it runs the code. Give's the verbose backstory and takes a while to completely run.

Then after the command is done running I check C:\Users and low and behold, all the users that SHOULD be gone are still there. And the same is true for the reg keys that SHOULD be gone.

Any advice? I'm a very novice at best coder, just trying to impress my boss and get my facility running with better efficiency.

1

There are 1 best solutions below

0
Jeff Zeitlin On

The LastUseTime format is NOT usable directly for date-time calculations in PowerShell. To convert it to the appropriate format, use [Management.ManagementDateTimeConverter]::ToDateTime():

Get-CimInstance win32_userprofile -verbose | 
    Where {[Management.ManagementDateTimeConverter]::ToDateTime($_.LastUseTime) -lt $(Get-Date).Date.AddDays(-x) } | 
    Remove-CimInstance -Verbose