There are many ways to Get the Current Logged in Username in Windows PowerShell. In this article let’s look at some of the easiest and best ways to fetch the current username using PowerShell.
Get the Current UserName in Windows PowerShell Command
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name # Returns Domain name and Username [Environment]::UserName # Output # Administrator
The above command will return the current logged in username as the output.
Command to Fetch Current User Domain and Machine Name in PowerShell
[Environment]::UserDomainName [Environment]::MachineName # Output # Gamerz # Askmein
The above commands will return you the Machine Name and the Domain name of the logged in user.There are few other techniques which you could use to get the Username. Below are some of the commands with the output.
PowerShell Command to Get the Username
If you want to get the current Logged In username then the best command to use is $(Get-WMIObject -class Win32_ComputerSystem | select username).username
I personally do not recommend using $env:username because it will fetch the username from the environment variables and we know that environment variables can be easily altered.
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name # Returns Domain name and Username $env:username # Returns username $(whoami) # Returns domain name and username $(Get-WMIObject -class Win32_ComputerSystem | select username).username # Returns the name of the Logged in user