Get Current User Name in PowerShell
You can easily get the current username in Windows PowerShell using whoami
to return domain\username as below
![Get current username in Windows PowerShell](https://debug.to/?qa=blob&qa_blobid=14102296139735838257)
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
![Get current logged-on username who runs the PowerShell in Windows PowerShell](https://debug.to/?qa=blob&qa_blobid=35287066737035824)
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
![Get current logged-on username who runs the PowerShell in Windows PowerShell](https://debug.to/?qa=blob&qa_blobid=35287066737035824)
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
![Get current logged-on username without domain in Windows PowerShell](https://debug.to/?qa=blob&qa_blobid=10943220585810349990)
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
![Get domain name in Windows PowerShell](https://debug.to/?qa=blob&qa_blobid=8222852092667388021)
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
![Powershell Get Domain and UserName in PowerShell using Win32_ComputerSystem](https://debug.to/?qa=blob&qa_blobid=17905152017742265650)
See Also