- Getting the Username from the HKEY_USERS values
- 9 Answers 9
- How do you find the current user in a Windows environment?
- 15 Answers 15
- PowerShell
- Not the answer you’re looking for? Browse other questions tagged windows batch-file or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- Get-User
- Syntax
- Description
- Examples
- Example 1
- Example 2
- Example 3
- Example 4
- Parameters
- Inputs
- Outputs
Getting the Username from the HKEY_USERS values
Is there a way to connect between the values under HKEY_USERS to the actual username?
I saw some similar questions, but most (if not all) talks about C# code, and my need is in VBScript.
9 Answers 9
If you look at either of the following keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist
You can find a list of the SIDs there with various values, including where their «home paths» which includes their usernames.
I’m not sure how dependable this is and I wouldn’t recommend messing about with this unless you’re really sure what you’re doing.
It is possible to query this information from WMI. The following command will output a table with a row for every user along with the SID for each user.
You can also export this information to CSV:
I have used this on Vista and 7. For more information see WMIC — Take Command-line Control over WMI.
Open Reg HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\
make a loop to get all subkeys
the subkeys you are interested with are those started with [S-1-5-21-] which means user (see key name [ProfileImagePath] they are always started with a path c:\Users)
Those starting with [S-1-5-21-12] are all local users
Those starting with [S-1-5-21-13] are all network users [if joined to Domained network] that are previously logged on the machine.
By searching for my userid in the registry, I found
You can use the command PSGetSid from Microsoft’s SysInternals team.
- Where the user is a domain/AD(LDAP) user, running this on any computer on the domain should give the same results.
- Where the user is local to the machine the command should either be run on that machine, or you should specify the computer via the optional parameter.
Update
If you use PowerShell, the following may be useful for resolving any AD users listed:
You could also refine the SID filter further to only pull back those SIDs which will resolve to an AD account if you wished; more on the SID structure here: https://technet.microsoft.com/en-us/library/cc962011.aspx
In the HKEY_USERS\oneyouwanttoknow\ you can look at \Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders and it will reveal their profile paths. c:\users\whothisis\Desktop , etc.
Done it, by a bit of creative programming,
Enum the Keys in HKEY_USERS for those funny number keys.
Enum the keys in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\
and you will find the same numbers. Now in those keys look at the String value: ProfileImagePath = «SomeValue» where the values are either:
«%systemroot%\system32\config\systemprofile». not interested in this one. as its not a directory path.
%SystemDrive%\Documents and Settings\LocalService — «Local Services» %SystemDrive%\Documents and Settings\NetworkService «NETWORK SERVICE»
%SystemDrive%\Documents and Settings\USER_NAME, which translates directly to the «USERNAME» values in most un-tampered systems, ie. where the user has not changed the their user name after a few weeks or altered the paths explicitly.
The proper way to do this requires leveraging the SAM registry hive (on Windows 10, this requires NT AUTHORITY\SYSTEM privileges). The information you require is in the the key: HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users\Names .
Each subkey is the username, and the default value in each subkey is a binary integer. This value (converted to decimal) actually corresponds to the last chunk of the of the SID.
Take «Administrator» for example, by default it is associated with the integer 0x1f4 (or 500).
So, in theory you could take the build a list of SIDS based on the subkey names of the HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\ProfileList key and/or HKEY_USERS key, parse out the the value after the last hyphen (-), and compare that to the info from the SAM hive.
If you don’t have NT AUTHORITY\SYSTEM privileges, the next best way to approach this may be to follow the other method described in the answers here.
How do you find the current user in a Windows environment?
When running a command-line script, is it possible to get the name of the current user?
15 Answers 15
You can use the username variable: %USERNAME%
Username:
Domainname:
You can get a complete list of environment variables by running the command set from the command prompt.
Just use this command in command prompt
It should be in %USERNAME% . Obviously this can be easily spoofed, so don’t rely on it for security.
Useful tip: type set in a command prompt will list all environment variables.
%USERNAME% is the correct answer in batch and other in Windows environments.
Another option is to use %USERPROFILE% to get the user’s path, like C:\Users\username .
The answer depends on which «command-line script» language you are in.
In the old cmd.exe command prompt or in a .bat or .cmd script, you can use the following:
%USERNAME% — Gets just the username.
%USERDOMAIN% — Gets the user’s domain.
PowerShell
In the PowerShell command prompt or a .ps1 or .psm1 script, you can use the following:
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name — Gives you the fully qualified username (e.g. Domain\Username). This is also the most secure method because it cannot be overridden by the user like the other $Env variables below.
$Env:Username — Gets just the username.
$Env:UserDomain — Gets the user’s domain.
$Env:ComputerName — Gets the name of the computer.
%USERNAME% will get you the username of the currently running process. Depending on how you are running your batch file, this is not necessarily the same as the name of the current user. For example, you might be running your batch file through a scheduled task, from a service, etc.
Here is a more sure way of getting the username of the currently logged on user by scraping the name of the user that started the explorer.exe task:
I use this method in writing batch files for testing.
Since you must include the password in plain text if authentication is required, I will only use it in a completely private environment where other users cannot view it or if a user seeing the password would bear no consequences.
Hope this helps someone out.
It’s always annoyed me how Windows doesn’t have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:
And just use that in your batch file.
In most cases, the %USERNAME% variable will be what you want.
However, if you’re running an elevated cmd shell, then %USERNAME% will report the administrator name instead of your own user name. If you want to know the latter, run:
Just type whoami in command prompt and you’ll get the current username.
This is the main difference between username variable and whoami command:
In a standard context, each connected user holds an explorer.exe process: The command [tasklist /V|find «explorer»] returns a line that contains the explorer.exe process owner’s, with an adapted regex it is possible to obtain the required value. This also runs perfectly under Windows 7.
In rare cases explorer.exe is replaced by another program, the find filter can be adapted to match this case. If the command return an empty line then it is likely that no user is logged on. With Windows 7 it is also possible to run [query session|find «>»].
As far as find BlueBearr response the best (while I,m running my batch script with eg. SYSTEM rights) I have to add something to it. Because in my Windows language version (Polish) line that is to be catched by «%%a %%b»==»User Name:» gets REALLY COMPLICATED (it contains some diacritic characters in my language) I skip first 7 lines and operate on the 8th.
Via powershell (file.ps1) I use the following
It returns the name of the user in the «Domain\Username» format. If you just want the username just write
The advantage is that It works with windows 10 windows 8 server 2016. As far as I remember with also other OS like Win7 etc. (not older) . And yeah via batch you can simply use
Not the answer you’re looking for? Browse other questions tagged windows batch-file or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Get-User
This cmdlet is available in on-premises Exchange and in the cloud-based service. Some parameters and settings may be exclusive to one environment or the other.
Use the Get-User cmdlet to view existing user objects in your organization. This cmdlet returns all objects that have user accounts (for example, user mailboxes, mail users, and user accounts).
For information about the parameter sets in the Syntax section below, see Exchange cmdlet syntax.
Syntax
Description
The Get-User cmdlet returns no mail-related properties for mailboxes or mail users. To view the mail-related properties for a user, you need to use the corresponding cmdlet based on the object type (for example, Get-Mailbox or Get-MailUser).
You need to be assigned permissions before you can run this cmdlet. Although this topic lists all parameters for the cmdlet, you may not have access to some parameters if they’re not included in the permissions assigned to you. To find the permissions required to run any cmdlet or parameter in your organization, see Find the permissions required to run any Exchange cmdlet.
Examples
Example 1
This example returns a summary list of all users in your organization.
Example 2
This example returns detailed information for the user named Coy Damon.
Example 3
This example retrieves information about users in the Marketing OU.
Example 4
This example uses the Filter parameter to retrieve information about all users that have the word Manager at the end of their title.
Parameters
The Anr parameter specifies a string on which to perform an ambiguous name resolution (ANR) search. You can specify a partial string and search for objects with an attribute that matches that string. The default attributes searched are:
- CommonName (CN)
- DisplayName
- FirstName
- LastName
- Alias
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Exchange Online Protection |
This parameter is available only in on-premises Exchange.
The Arbitration switch is required to return arbitration mailboxes in the results. You don’t need to specify a value with this switch.
Arbitration mailboxes are system mailboxes that are used for storing different types of system data and for managing messaging approval workflow.
To return arbitration mailboxes that are used to store audit log settings or data, don’t use this switch. Instead, use the AuditLog or AuxAuditLog switches.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019 |
This parameter is available only in on-premises Exchange.
The AuditLog switch is required to return audit log mailboxes in the results. You don’t need to specify a value with this switch.
Audit log mailboxes are arbitration mailboxes that are used to store audit log settings.
To return other types of arbitration mailboxes, don’t use this switch. Instead, use the Arbitration switch.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2016, Exchange Server 2019 |
This parameter is available only in on-premises Exchange.
The AuxAuditLog switch is required to return auxiliary audit log mailboxes in the results. You don’t need to specify a value with this switch.
Audit log mailboxes are arbitration mailboxes that are used to store audit log settings.
To return other types of arbitration mailboxes, don’t use this switch. Instead, use the Arbitration switch.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2016, Exchange Server 2019 |
This parameter is available only in on-premises Exchange.
The Credential parameter specifies the username and password that’s used to run this command. Typically, you use this parameter in scripts or when you need to provide different credentials that have the required permissions.
A value for this parameter requires the Get-Credential cmdlet. To pause this command and receive a prompt for credentials, use the value (Get-Credential) . Or, before you run this command, store the credentials in a variable (for example, $cred = Get-Credential ) and then use the variable name ( $cred ) for this parameter. For more information, see Get-Credential.
Type: | PSCredential |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019 |
This parameter is available only in on-premises Exchange.
The DomainController parameter specifies the domain controller that’s used by this cmdlet to read data from or write data to Active Directory. You identify the domain controller by its fully qualified domain name (FQDN). For example, dc01.contoso.com.
Type: | Fqdn |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019 |
The Filter parameter uses OPath syntax to filter the results by the specified properties and values. The search criteria uses the syntax «Property -ComparisonOperator ‘Value'» .
- Enclose the whole OPath filter in double quotation marks » «. If the filter contains system values (for example, $true , $false , or $null ), use single quotation marks ‘ ‘ instead. Although this parameter is a string (not a system block), you can also use braces < >, but only if the filter doesn’t contain variables.
- Property is a filterable property. For more information about the filterable properties, see Filterable properties for the Filter parameter.
- ComparisonOperator is an OPath comparison operator (for example -eq for equals and -like for string comparison). For more information about comparison operators, see about_Comparison_Operators.
- Value is the property value to search for. Enclose text values and variables in single quotation marks ( ‘Value’ or ‘$Variable’ ). If a variable value contains single quotation marks, you need to identify (escape) the single quotation marks to expand the variable correctly. For example, instead of ‘$User’ , use ‘$($User -Replace «‘»,»»»)’ . Don’t enclose integers or system values (for example, 500 , $true , $false , or $null ).
You can chain multiple search criteria together using the logical operators -and and -or . For example, «Criteria1 -and Criteria2» or «(Criteria1 -and Criteria2) -or Criteria3» .
For detailed information about OPath filters in Exchange, see Additional OPATH syntax information.
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Security & Compliance Center, Exchange Online Protection |
The Identity parameter the user that you want to view. You can use any value that uniquely identifies the user. For example:
- Name
- Distinguished name (DN)
- Canonical DN
- GUID
Type: | UserIdParameter |
Position: | 1 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Security & Compliance Center, Exchange Online Protection |
This parameter is available only in on-premises Exchange.
The IgnoreDefaultScope switch tells the command to ignore the default recipient scope setting for the Exchange Management Shell session, and to use the entire forest as the scope. This allows the command to access Active Directory objects that aren’t currently available in the default scope.
Using the IgnoreDefaultScope switch introduces the following restrictions:
- You can’t use the DomainController parameter. The command uses an appropriate global catalog server automatically.
- You can only use the DN for the Identity parameter. Other forms of identification, such as alias or GUID, aren’t accepted.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019 |
This parameter is available only in the cloud-based service.
The IsVIP switch filters the results by priority accounts.
For more information about priority accounts, see Manage and monitor priority accounts.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Online, Exchange Online Protection |
The OrganizationalUnit parameter filters the results based on the object’s location in Active Directory. Only objects that exist in the specified location are returned. Valid input for this parameter is an organizational unit (OU) or domain that’s returned by the Get-OrganizationalUnit cmdlet. You can use any value that uniquely identifies the OU or domain. For example:
- Name
- Canonical name
- Distinguished name (DN)
- GUID
Type: | OrganizationalUnitIdParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Exchange Online Protection |
The PublicFolder switch is required to return public folder mailboxes in the results. You don’t need to specify a value with this switch.
Public folder mailboxes are specially designed mailboxes that store the hierarchy and content of public folders.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Security & Compliance Center |
This parameter is available only in on-premises Exchange.
The ReadFromDomainController switch specifies that information should be read from a domain controller in the user’s domain. If you run the command Set-AdServerSettings -ViewEntireForest $true to include all objects in the forest and you don’t use the ReadFromDomainController switch, it’s possible that information will be read from a global catalog that has outdated information. When you use the ReadFromDomainController switch, multiple reads might be necessary to get the information. You don’t have to specify a value with this switch.
By default, the recipient scope is set to the domain that hosts your Exchange servers.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019 |
The RecipientTypeDetails parameter filters the results by the specified user subtype. Valid values are:
- DisabledUser
- DiscoveryMailbox
- EquipmentMailbox
- GuestMailUser
- LegacyMailbox
- LinkedMailbox
- LinkedUser
- MailUser
- PublicFolderMailbox
- RemoteEquipmentMailbox
- RemoteRoomMailbox
- RemoteSharedMailbox
- RemoteTeamMailbox
- RemoteUserMailbox
- RoomMailbox
- SchedulingMailbox
- SharedMailbox
- TeamMailbox
- User
- UserMailbox
You can specify multiple values separated by commas.
Type: | RecipientTypeDetails [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Security & Compliance Center, Exchange Online Protection |
The ResultSize parameter specifies the maximum number of results to return. If you want to return all requests that match the query, use unlimited for the value of this parameter. The default value is 1000.
Type: | Unlimited |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Security & Compliance Center, Exchange Online Protection |
The SortBy parameter specifies the property to sort the results by. You can sort by only one property at a time. The results are sorted in ascending order.
If the default view doesn’t include the property you’re sorting by, you can append the command with | Format-Table -Auto Property1,Property2. PropertyX . to create a new view that contains all of the properties that you want to see. Wildcards (*) in the property names are supported.
You can sort by the following properties:
- Name
- DisplayName
- City
- FirstName
- LastName
- Office
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2010, Exchange Server 2013, Exchange Server 2016, Exchange Server 2019, Exchange Online, Security & Compliance Center, Exchange Online Protection |
This parameter is available only in on-premises Exchange.
This parameter is reserved for internal Microsoft use.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | False |
Accept wildcard characters: | False |
Applies to: | Exchange Server 2016, Exchange Server 2019 |
Inputs
To see the input types that this cmdlet accepts, see Cmdlet Input and Output Types. If the Input Type field for a cmdlet is blank, the cmdlet doesn’t accept input data.
Outputs
To see the return types, which are also known as output types, that this cmdlet accepts, see Cmdlet Input and Output Types. If the Output Type field is blank, the cmdlet doesn’t return data.