Purging disused Windows accounts

  Kiến thức lập trình

For months, I’ve been looking for a way to automate cleaning up old Windows user accounts using PowerShell in an enterprise environment where I don’t have authority to make changes to GPO or AD.

I can’t use third party applications in this environment, so it needs to be either PowerShell or batch script.

I’ve read through several articles on StackOverflow and similar sites and have come up with a mostly functional one-liner:

Get-WmiObject -Class Win32_UserProfile | Where-Object { $_.Loaded -eq 'False' -and $_.Special -eq 'False' -and $_.LocalPath -like "C:Users*" -and $_.ConvertToDateTime($_.LastUseTime) -lt (Get-Date).AddDays(-90) } | Remove-WmiObject -Confirm:$false -AsJob

The only apparent problem with the command above is that the LastUseTime property of Win32_UserProfile doesn’t appear to be consistently and accurately report the date of last use. I’ve also tried variations of the same using the LastWriteTime property of a local file, but am finding that those are being frequently updated by a system process outside my control.

I’ve tried several variations on based on last use or last logon properties of Win32_UserProfile and Win32_NetworkLoginProfile, but the dates and times are being modified by something other than account login.

I’ve tried using Get-Event to pull event IDs for Windows login, but the enterprise has blocked reading Event Viewer through PowerShell.

I’ve tried using Get-Childitem to pull the LastWriteTime property of files within the user accounts, but they appear to be getting updated timestamps while the account isn’t logged in.

I’ve been unable to find a registry container or key that might contain the info.

New contributor

Scott is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT