Get Current User Name in PowerShell
You can easily get the current username in Windows PowerShell using whoami
to return domain\username as below

There are also many ways to get the current logged on username in Windows PowerShell as the following:
- Using
System.Security.Principal.WindowsIdentity
- Using
$env
- Using
Win32_ComputerSystem
1) Get current logged-on username in Windows PowerShell
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
This example helps you to get the current user who runs the PowerShell domain\username
. so if you are run the Powershell as a different user it will get the current user who runs the PowerShell, not the currently logged-on user to the machine.
Output

1) Get current logged-on username in Windows PowerShell
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
This example helps you to get the current user who runs the PowerShell domain\username
. so if you are run the Powershell as a different user it will get the current user who runs the PowerShell, not the currently logged-on user to the machine.
Output

2) Get current logged-on username without domain in Windows PowerShell
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name.split("\")[1]
Or
$env:UserName
This example helps you to get the current user who runs the PowerShell without domain.
Output

3) Get domain name in Windows PowerShell
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name.split("\")[0]
Or
$env:UserDomain #not recommened
This example helps you to get only the current domain name.
Output

4) Get current logged-on username to machine in PowerShell
$userInfo=((Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username) -split '\\' )
$userInfo[0]+"\"+$userInfo[1]
This example helps you to get the logged-in user info like Domain Name $userInfo[0]
and User Name $userInfo[1]
or domain\username $userInfo[0]+"\"+$userInfo[1]
. but if you are running the Powershell as a different user it will not get the current user who runs the PowerShell, it only gets the currently logged-on user to the machine.
Output

See Also