You got admin?

1 minute read

When creating certain scripts it is nice to know if the current user is an administrator to the workstation or not. This can be done in a few ways, Powershell and also .NET.

First we can use ADSI to query the computer and get the objects found in group specified. In this example we query the administrators group using the current user, then if the current user is in the group, we have a match.

$user = $env:USERNAME;
$group = "Administrators";
$groupObj =[ADSI]"WinNT://./$group,group"
$membersObj = @($groupObj.psbase.Invoke("Members"))
$members = ($membersObj | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)})

If ($members -contains $user) {
  Write-Host $user -foregroundcolor "Red" -NoNewLine; Write-Host " exists in the local group $group"
} Else {
  Write-Host "$user not exists in the local group $group"
}

Now to speed up that process we can harness .NET classes in Powershell. We will use the [Security.Principal.WindowsPrincipal] class.

([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

From here we get the current users identity and check if they are in the role of Administrator. This is a lot quicker and faster as well since it is in one line and can be used in a quicker manner to restart the script as an administrator.

if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }

To run a Powershell script and get around the Execution Policy, we can start Powershell, specify the execution policy and specify the Powershell script we want to run.

PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%~dp0Server_Setup.ps1""' -Verb RunAs}"