Search code examples
windowspowershellscheduled-taskswindows-server-2012elevated-privileges

Powershell to open a powershell console in administrator mode without the UAC dialog box and perform some task


I use a user that has admin role. However, by default, the scripts run in UAC mode and not as Administrator. Is it possible to open a powershell console with powershell script without the UAC dialog box?

I tried elevating the task I want to do as follow but it gives me a dialog box which needs to be attended:

# Get the ID and security principal of the current user account
$myWindowsID = [System.Security.Principal.WindowsIdentity]::GetCurrent();
$myWindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($myWindowsID);

# Get the security principal for the administrator role
$adminRole = [System.Security.Principal.WindowsBuiltInRole]::Administrator;

# Check to see if we are currently running as an administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
    # We are running as an administrator, so change the title and background colour to indicate this
    $Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)";
    $Host.UI.RawUI.BackgroundColor = "DarkBlue";
    Clear-Host;
}
else {
    # We are not running as an administrator, so relaunch as administrator

    # Create a new process object that starts PowerShell
    $newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";


    # Indicate that the process should be elevated
    $newProcess.Verb = "runas";

    # Start the new process
    [System.Diagnostics.Process]::Start($newProcess);

    # Exit from the current, unelevated, process
    Exit;
}

#DOING SOME TASK HERE

However, this opens up a UAC dialog box that confirms if I wish to open powershell in Administrator mode.

Another way that I have tried is to open the powershell console in Administrator mode by default (I use WS 2012 and the way to do this is the same as done in Windows 10). However, I do not own the rights to make changes like this to the system as the DevOps refrains me to do so. Is there any other way through powershell scripting to deal with this?


Solution

  • You could - as a workaround - create a 'scheduled' task which is set up to run elevated and trigger that task from your initial PowerShell.

    See here for how to set up such a task and here for how to trigger it.