Running powershell scripts as administrator

Even though a user is in the Administrators group, when opening a powershell console, or running a scheduled task, even with “highest privileges”, the powershell script does not run with administrator privileges. This usually results in the following error:

PS C:\Users\josh> stop-service filebeat
stop-service : Service 'filebeat (filebeat)' cannot be stopped due to the following error: Cannot open filebeat
service on computer '.'.
At line:1 char:1
+ stop-service filebeat
+ ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (System.ServiceProcess.ServiceController:ServiceController) [Stop-Service],
    + FullyQualifiedErrorId : CouldNotStopService,Microsoft.PowerShell.Commands.StopServiceCommand

PS C:\Users\josh> 

One way to solve this problem is to refactor the powershell script to check for administrator privileges and launch a new process using the RunAs Verb if not administrator.

# Get the ID and security principal of the current user account
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
   # We are running "as Administrator" - so change the title and background color to indicate this
   $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
   $Host.UI.RawUI.BackgroundColor = "DarkBlue"
	# We are not running "as Administrator" - so relaunch as administrator
	# Create a new process object that starts PowerShell
	$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
	# Specify the current script path and name as a parameter
	$newProcess.Arguments = $myInvocation.MyCommand.Definition;
	# Indicate that the process should be elevated
	$newProcess.Verb = "runas";
	# Start the new process
	# Exit from the current, unelevated, process

Thanks to lokiwins at Reddit for passing this along.

Leave a Reply

Your email address will not be published. Required fields are marked *