How do I get the current username in Windows PowerShell?
In my case, I needed to retrieve the username to enable the script to change the path, ie. c:\users\%username%\
. I needed to start the script by changing the path to the users desktop. I was able to do this, with help from above and elsewhere, by using the get-location applet.
You may have another, or even better way to do it, but this worked for me:
$Path = Get-Location
Set-Location $Path\Desktop
I have used $env:username
in the past, but a colleague pointed out it's an environment variable and can be changed by the user and therefore, if you really want to get the current user's username, you shouldn't trust it.
I'd upvote Mark Seemann's answer: [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
But I'm not allowed to. With Mark's answer, if you need just the username, you may have to parse it out since on my system, it returns hostname\username
and on domain joined machines with domain accounts it will return domain\username
.
I would not use whoami.exe
since it's not present on all versions of Windows, and it's a call out to another binary and may give some security teams fits.
I found it:
$env:UserName
There is also:
$env:UserDomain
$env:ComputerName
If you're used to batch, you can call
$user=$(cmd.exe /c echo %username%)
This basically steals the output from what you would get if you had a batch file with just "echo %username%".
[Environment]::UserName
returns just the user name. E.g. bob
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
returns the user name, prefixed by its domain where appropriate. E.g. SOMEWHERENICE\bob
$env:username
is the easiest way