How do I get the current username in Windows PowerShell?

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

How do I get the current username in Windows PowerShell?

相关标签:
15条回答
  • 2020-11-28 01:52

    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)
  • 2020-11-28 01:54

    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.

    0 讨论(0)
  • 2020-11-28 01:57

    I found it:

    $env:UserName
    

    There is also:

    $env:UserDomain
    $env:ComputerName
    
    0 讨论(0)
  • 2020-11-28 01:57

    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%".

    0 讨论(0)
  • 2020-11-28 01:58

    [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

    0 讨论(0)
  • 2020-11-28 01:59

    $env:username is the easiest way

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