Whats the best/easiest way to test for administrative rights in a PowerShell script?
I need to write a script that requires administrative rights and want to know the best way to achieve it.
Open PowerShell by right-clicking on the Windows start menu and choose the one that says, Administrator. The first command you'll need to enter is whoami and press enter. The second command to enter is Get- LocalUser -Name You username here | Select Principal Source. Don't forget to press enter.
Select Control Panel. In the Control Panel window, double click on the User Accounts icon. In the lower half of the User Accounts window, under the or pick an account to change heading, find your user account. If the words “Computer administrator” are in your account's description, then you are an administrator.
Run PowerShell as an Administrator from Start MenuStep 1: In windows 10, click on the 'Start' button to open the Start menu. Step 2: Now scroll to the Windows PowerShell shortcut folder then, right-click on the Windows PowerShell option and select the run as administrator option.
Open the task manager by using the shortcut keys Ctrl+Alt+Del. Explore the File tab and Run a new task by clicking on the option given. In the PowerShell type the same command start-process PowerShell -verb runas and hit enter to run it as administrator.
This is the little function I have in a security module:
function Test-IsAdmin {
try {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal -ArgumentList $identity
return $principal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator )
} catch {
throw "Failed to determine if the current user has elevated privileges. The error was: '{0}'." -f $_
}
<#
.SYNOPSIS
Checks if the current Powershell instance is running with elevated privileges or not.
.EXAMPLE
PS C:\> Test-IsAdmin
.OUTPUTS
System.Boolean
True if the current Powershell is elevated, false if not.
#>
}
In Powershell 4.0 you can use requires at the top of your script:
#Requires -RunAsAdministrator
Outputs:
The script 'MyScript.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With