When running a command-line script, is it possible to get the name of the current user?
When running a command-line script, is it possible to get the name of the current user?
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.
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.
This is the main difference between username variable and whoami command:
C:\Users\user.name>echo %username%
user.name
C:\Users\user.name>whoami
domain\user.name
DOMAIN = bios name of the domain (not fqdn)
Via powershell (file.ps1) I use the following
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
It returns the name of the user in the "Domain\Username" format. If you just want the username just write
$username = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.Split("\")[1]
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
$username = &whoami