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


当前回答

在Windows上,你可以:

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

其他回答

我没有看到任何基于Add-Type的例子。这里是一个使用GetUserName直接从advapi32.dll。

$sig = @'
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool GetUserName(System.Text.StringBuilder sb, ref Int32 length);
'@

Add-Type -MemberDefinition $sig -Namespace Advapi32 -Name Util

$size = 64
$str = New-Object System.Text.StringBuilder -ArgumentList $size

[Advapi32.util]::GetUserName($str, [ref]$size) |Out-Null
$str.ToString()

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

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

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

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

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

在Windows上,你可以:

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