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


当前回答

现在PowerShell Core(又名v6)已经发布了,人们可能想要编写跨平台脚本,这里的许多答案都不能在Windows以外的任何平台上工作。

[Environment]::UserName似乎是在PowerShell Core支持的所有平台上获得当前用户名的最佳方法,如果你不想在你的代码中添加平台检测和特殊的外壳。

其他回答

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

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

我找到了:

$env:UserName

还有:

$env:UserDomain
$env:ComputerName

在Windows上,你可以:

[System.Security.Principal.WindowsIdentity]::GetCurrent().Name

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

$username=( ( Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username ) -split '\\' )[1]

美元的用户名

第二个用户名仅用于复制和粘贴时显示。