获取当前脚本Powershell是否以管理员身份执行(以管理员身份运行)
问题描述:
我拥有Windows User C#的用户UserInstallerMoss凭据。获取当前脚本Powershell是否以管理员身份执行(以管理员身份运行)
Windows服务使用凭据UserInstallerMoss执行EXE控制台Aplicaction C#。
EXE控制台Aplicaction使用凭据UserInstallerMoss执行powershell.exe。
服务器是Windows Server 2012 Enterprise。 UAC被禁用。
UserinstallerMOss是本地管理员
PowerShell函数返回$真值:
$ok = IsCurrentUserAdmin
$ok = IsCurrentUserAdmin2
但脚本失败有关 “拒绝访问”
nativehr:0X80070005 OWSSVR.DLL - 访问被拒绝
如果当前脚本Powershell以“以管理员身份运行”执行,我该如何获取?
如何获取脚本Powershell中的当前用户是管理员?
我的函数返回true,但可能是错误的?
PowerShell函数:
Function IsCurrentUserAdmin
{
$ident = [Security.Principal.WindowsIdentity]::GetCurrent()
foreach ($groupIdent in $ident.Groups)
{
if ($groupIdent.IsValidTargetType([Security.Principal.SecurityIdentifier]))
{
$groupSid = $groupIdent.Translate([Security.Principal.SecurityIdentifier])
if ($groupSid.IsWellKnown("AccountAdministratorSid") -or $groupSid.IsWellKnown("BuiltinAdministratorsSid"))
{
return $TRUE
}
}
}
return $FALSE
}
Function IsCurrentUserAdmin2
{
$user = [Security.Principal.WindowsIdentity]::GetCurrent();
(New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
答
如果您希望测试脚本运行高架:
function Test-RunningElevated{
# returns True if running elevated, otherwise returns False
$windowsIdentity=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$windowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($windowsIdentity)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
Write-Output ($windowsPrincipal.IsInRole($adm))
}
如果你想测试,如果用户正在运行的脚本是本地管理员组的成员:
function Test-LocalAdministrator{
$currentUser = $env:USERNAME
$currentComputer = $env:COMPUTERNAME
$adminGroup = [ADSI]"WinNT://$currentComputer/Administrators"
$adminGroup.Members() | ForEach-Object{
$member = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
if($member -eq $currentUser){
Write-Output $true
break
}
}
Write-Output $false
}
使用它们是这样的:
if(Test-RunningElevated){
# code to run goes here
}
else{
Write-Warning 'This script needs to be run elevated!'
}
请注意,Test-LocalAdministrator只检查直接成员资格。
这与IsCurrentUserAdmin2功能相同 – Kiquenet 2014-09-03 08:52:08
即使您运行脚本提升,它也会返回false? – ojk 2014-09-03 08:53:19