Tuesday, January 13, 2015

(PowerShell) Enumerating Local User Accounts

This was mildly annoying so I thought I would put it here so next time I run into this I know how to do it. I wanted to simply enumerate all of the standard user accounts on the LocalMachine using a one liner PowerShell cmdlet. Most of methods I found online with a google search said to use [ASDI]. This was more convoluted than I wanted to get to do this seemingly simple thing.

After stewing for a bit I started digging through the Get-WmiObject cmdlet and there it was!!!

-Class Win32_UserAccount


So I took a look at the available properties and output the usernames only.

Get-WmiObject -Class Win32_UserAccount | Get-Member













So I just formatted the output to include just the Name property and there it is.

Get-WmiObject -Class Win32_UserAccount | Format-List -Property Name









But we are not going to stop there :)
I went ahead and pulled just the admin account.

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Name -eq "Administrator"}









That was only a subset of the properties so I used Format-List -Property * to pull up the rest of them

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Name -eq "Administrator"} | Format-List -Property *


















Now that I can see all of the properties I can check for certain properties across all of the accounts. For example I can list all of the accounts that are currently disabled.

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Disabled -eq $true}












If I break my one line rule I can even modify properties of the user object, for example lets say that I wanted to enable the Administrator account for some reason (Don't do this, I am just figuring out how this works and enabling the Administrator account is a bad idea).

[Note: The .Put() thing, this threw me for a few minutes. Remember when you use any of the Get- commands what you are actually doing is grabbing templates of the objects and then filling them with data PowerShell grabs from the OS. What I changed when I set Disabled = $false is the value in the new object I created. The .Put() command takes my object and saves it back to OS so that the changes take effect. Without the .Put() nothing changes on the OS]

$tempuser = Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Name -eq "Administrator"}

$tempuser.Disabled = $false

$tempuser.Put()



Now if I run my account disabled test from above I get this.

Get-WmiObject -Class Win32_UserAccount | Where-Object{$_.Disabled -eq $true}




No comments:

Post a Comment