How do I get the current username in Windows PowerShell?

Viewed 803129

How do I get the current username in Windows PowerShell?

14 Answers

I found it:

$env:UserName

There is also:

$env:UserDomain
$env:ComputerName

On Windows, you can:

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
$username=( ( Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username ) -split '\\' )[1]

$username

The second username is for display only purposes only if you copy and paste it.

I find easiest to use: cd $home\Desktop\

will take you to current user desktop

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

Related