简体   繁体   中英

How to get all windows user accounts associated with a PC

My work-pc user account is related to my work's active directory domain, but I also have 3 local Windows user accounts. I want to programmatically get usernames of these 4 accounts. I've tried using WMI and some powershell commands, but I either get only 3 local accounts or ALL domain accounts (me and all my coworkers). I can see what I need if go to User Accounts in control panel. Is there a way I can domain account only related to a particular machine.

Basically I want all these:

That list of profiles is kept in the registry at:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

So you can read that registry key from your code. Those keys contain the SID of the accounts, which you can then translate into DOMAIN\username format, like this:

using (var profileList = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList")) {
    foreach (string keyName in profileList.GetSubKeyNames()) {
        using (var profile = profileList.OpenSubKey(keyName)) {
            if ((int) profile.GetValue("FullProfile", 0) != 1) continue;

            var sid = new SecurityIdentifier(keyName);
            Console.WriteLine(sid.Translate(typeof(NTAccount)));
        }
    }
}

Checking if the FullProfile value is 1 is just to exclude the SYSTEM , LOCAL SERVICE and NETWORK SERVICE accounts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM