如何在Windows PowerShell中获取当前用户名?


当前回答

[Environment]::UserName只返回用户名。例如,鲍勃 [System.Security.Principal.WindowsIdentity]:: GetCurrent()。Name返回用户名,在适当的地方加上域前缀。例如SOMEWHERENICE \鲍勃

其他回答

$env:用户名是最简单的方法

如果你习惯批处理,你可以打电话

$user=$(cmd.exe /c echo %username%)

这基本上窃取了如果你有一个只有“echo %username%”的批处理文件的输出。

[Environment]::UserName只返回用户名。例如,鲍勃 [System.Security.Principal.WindowsIdentity]:: GetCurrent()。Name返回用户名,在适当的地方加上域前缀。例如SOMEWHERENICE \鲍勃

只是在其他人工作的基础上:

[String] ${stUserDomain},[String]  ${stUserAccount} = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name.split("\")

我过去使用过$env:username,但同事指出它是一个环境变量,可以由用户更改,因此,如果你真的想获得当前用户的用户名,你不应该相信它。

我赞同马克·西曼的回答: [System.Security.Principal.WindowsIdentity]:: GetCurrent () . name

但是我不被允许。有了Mark的答案,如果你只需要用户名,你可能不得不解析出来,因为在我的系统上,它返回主机名\用户名,在域加入的机器上,它将返回域\用户名。

我不会使用whoami.exe,因为它不是在所有版本的Windows上都存在,而且它是对另一个二进制文件的调用,可能会让一些安全团队感到不适。