Powershell: Add a platform agnostic way to detect when running elevated

Created on 23 Jul 2018  路  7Comments  路  Source: PowerShell/PowerShell

When writing a PowerShell script, it would be nice to know if you're running in an elevated context (UAC in Windows, as root on *nix). You can do platform-specific things today, but it should be easily available without regard to platform.

Issue-Question WG-Engine Waiting - DotNetCore

Most helpful comment

CoreFx has an open issue to add API support: https://github.com/dotnet/corefx/issues/27304

Depending on how that goes (whether it's Unix specific, for example), perhaps we should consider a $IsAdmin automatic variable.

All 7 comments

CoreFx has an open issue to add API support: https://github.com/dotnet/corefx/issues/27304

Depending on how that goes (whether it's Unix specific, for example), perhaps we should consider a $IsAdmin automatic variable.

We have Test-IsElevated in out HelpersCommon.psm1. We could re-implement it on C#. Although the use of whoami/id is under question.

Looks like the CoreFx issue was closed and the recommended solution was to:

https://github.com/dotnet/runtime/issues/25118#issuecomment-367407469

To check if you are running as root on Unix:

  1. add a PackageReference to Mono.Posix.NETStandard
  2. Change IsAdminstrator to the following:
        public static bool IsAdministrator =>
            RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
                new WindowsPrincipal(WindowsIdentity.GetCurrent())
                    .IsInRole(WindowsBuiltInRole.Administrator) :
                Mono.Unix.Native.Syscall.geteuid() == 0; 

This is what I landed on:

$isDesktop = ($PSVersionTable.PSEdition -eq "Desktop")

if ($isDesktop -or $IsWindows) {
    $windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $windowsPrincipal = new-object 'System.Security.Principal.WindowsPrincipal' $windowsIdentity
    $isAdmin = $windowsPrincipal.IsInRole("Administrators") -eq 1
}
else {
    $isAdmin = ((& id -u) -eq 0)
}

Doesn't make sense to add a reference to Mono.Postix.NETStandard from PowerShell.

It is better to have in .Net.

.Net team asks to open new issue with API proposal. If you want to get any progress I suggest to open such issue there while they plans .Net 6.0.

@iSazonov This doesn't need to be a .NET feature. It could absolutely be a PowerShell feature.

We prefer to follow .Net in the repository.

The API is problematic because it depends on platforms. It should take into account all Unix clones and specific "platforms" like WebAssembly/Blazor. This requires complex testing and discussion.

Was this page helpful?
0 / 5 - 0 ratings