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.