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


当前回答

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

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

其他回答

有时,Username属性在Win32_ComputerSystem中没有数据,即使有用户登录。对我来说有用的是使用quser并解析输出。这并不完美,但很有效。例如:

$quserdata = @()
$quserdata = quser
$userid = ($quserdata[1] -split ' ')[1]
$userid 

注意:如果以登录用户的身份运行,quser会在输出中添加'>'符号。然后您需要删除该符号,但这主要用于作为系统或其他帐户运行的代码,而不是登录的帐户。

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

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

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

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

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

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

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

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