如何在PowerShell中获取当前用户名?
发布于 2010-01-18 19:52:53
我找到了:
$env:UserName还有:
$env:UserDomain
$env:ComputerName发布于 2010-01-18 19:54:21
在Windows上,您可以:
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name发布于 2015-04-30 05:49:06
我认为总结和比较给定的答案是有价值的。
如果您想要访问
(更简单/更短/更难忘的选项)
[Environment]::UserName -- @ThomasBratt$env:username -- @Eoinwhoami -- @galaktor如果您想要访问
(更可靠的选项)
[System.Security.Principal.WindowsIdentity]::GetCurrent().Name -- @MarkSeemann如果您想要已登录用户的名称
(而不是运行PowerShell实例的用户名)
this other forum上的
$(Get-WMIObject -class Win32_ComputerSystem | select username).username -- @TwonOfAn比较
@Kevin Panko对@Mark Seemann的回答的评论涉及到选择一个类别而不是另一个类别:
Windows访问令牌方法是最安全的答案,因为$env:USERNAME可以由用户更改,但这样做不会欺骗用户。
简而言之,Window环境变量选项更简洁,访问令牌选项更可靠。
我不得不在我通过模拟从C#应用程序运行的PowerShell脚本中使用@Mark Seemann的Windows access token方法。
使用我的用户帐户运行C#应用程序,并将PowerShell脚本作为服务帐户运行。由于我在C#中运行PowerShell脚本的方式的限制,PowerShell实例使用我的用户帐户的环境变量,即使它是作为服务帐户用户运行的。
在此设置中,环境变量选项返回我的帐户名,Windows访问令牌选项返回服务帐户名(这是我想要的),登录用户选项返回我的帐户名。
测试
此外,如果您想自己比较这些选项,这里有一个脚本,您可以使用它以另一个用户的身份运行脚本。您需要使用Get-Credential cmdlet获取凭据对象,然后使用脚本运行此脚本,以另一个用户作为参数1运行,将凭据对象作为参数2运行。
使用:
$cred = Get-Credential UserTo.RunAs
Run-AsUser.ps1 "whoami; pause" $cred
Run-AsUser.ps1 "[System.Security.Principal.WindowsIdentity]::GetCurrent().Name; pause" $credRun-AsUser.ps1脚本内容:
param(
[Parameter(Mandatory=$true)]
[string]$script,
[Parameter(Mandatory=$true)]
[System.Management.Automation.PsCredential]$cred
)
Start-Process -Credential $cred -FilePath 'powershell.exe' -ArgumentList 'noprofile','-Command',"$script"https://stackoverflow.com/questions/2085744
复制相似问题