You got admin?

30 Aug, 2019

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.


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}"

Tags: coding, powershell


If there are replies, they will show below.

Found an issue? Edit on Github

← Back home