How do I get the current username in Windows PowerShell?

后端 未结 15 2724
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 01:35

How do I get the current username in Windows PowerShell?

相关标签:
15条回答
  • 2020-11-28 02:13

    I'd like to throw in the whoami command, which basically is a nice alias for doing %USERDOMAIN%\%USERNAME% as proposed in other answers.

    Write-Host "current user:"
    Write-Host $(whoami)
    
    0 讨论(0)
  • 2020-11-28 02:13

    Now that PowerShell Core (aka v6) has been released, and people may want to write cross-platform scripts, many of the answers here will not work on anything other than Windows.

    [Environment]::UserName appears to be the best way of getting the current username on all platforms supported by PowerShell Core if you don't want to add platform detection and special casing to your code.

    0 讨论(0)
  • 2020-11-28 02:14

    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

    0 讨论(0)
提交回复
热议问题