PowerShell - If Admin

PowerShell - If Admin

Published
1 min read

Table of Contents

Determine If PowerShell User Is An Administrator

Hello, Explorer! I have a quick tip for you.

This PowerShell command creates a new instance of the WindowsPrincipal class and passes in the current user’s WindowsIdentity. It then calls the IsInRole method to determine whether the user is a member of the built-in Administrators role.

If the command returns true, the current user has administrative privileges on the local machine, and if it returns false, the user does not have administrative privileges.

This command can be useful in PowerShell scripts or command-line operations that require elevated privileges or to check if a user has administrative access before running certain actions.

In reality this is only necessary on Windows. On other unix based systems the user would just run with sudo.

if($IsWindows){
    $isAdmin = (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

    if ($isAdmin) {
        Write-Host "You have administrative privileges!"
    }
    else {
        Write-Host "You do not have administrative privileges!"
    }
}

This is a PowerShell command that checks whether the current user is a member of the local Administrators group on a Windows machine.