Finding User Account with WMI

by May 24, 2013

WMI represents all kinds of physical and logical entities on your machine. It also has classes that represent user accounts which include both local and domain accounts.

This piece of code returns the user account of the currently logged on user:

Get-WmiObject -Class Win32_UserAccount -Filter "Name='$env:username' and Domain='$env:userdomain'"

As always, the returned object holds a lot more information when you make PowerShell display all of its properties:

Get-WmiObject -Class Win32_UserAccount -Filter "Name='$env:username' and Domain='$env:userdomain'" 
| Select-Object * 

The returned information may look similar to this:

So you now can use all of this information to create test functions. The next function, for example, checks whether the currently logged on user is a local account or a domain account:

function Test-LocalUser
{   
    param(
      $UserName = $env:username,
      $Domain = $env:userdomain
    )

    (Get-WmiObject -Class Win32_UserAccount -Filter "Name='$UserName' and Domain='$Domain'")
    .LocalAccount
}

Twitter This Tip! ReTweet this Tip!