Запустить скрипт от имени администратора windows

On my Windows 7 Desktop, I have script.ps1, which needs admin privileges (it starts a service). I want to click on this script and run it with admin privileges.

What’s the easiest way to accomplish this?

asked Feb 12, 2010 at 21:46

Sajee's user avatar

0

Here is one way of doing it, with the help of an additional icon on your desktop. I guess you could move the script someone else if you wanted to only have a single icon on your desktop.

  1. Create a shortcut to your Powershell script on your desktop
  2. Right-click the shortcut and click Properties
  3. Click the Shortcut tab
  4. Click Advanced
  5. Select Run as Administrator

You can now run the script elevated by simple double-clicking the new shortcut on your desktop.

answered Feb 13, 2010 at 12:58

Kez's user avatar

KezKez

16.6k15 gold badges67 silver badges94 bronze badges

6

On UAC-enabled systems, to make sure a script is running with full admin privileges, add this code at the beginning of your script:

param([switch]$Elevated)

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

'running with full privileges'

Now, when running your script, it will call itself again and attempt to elevate privileges before running.
The -elevated switch prevents it from repeating if something fails.

You may remove the -noexit switch if the terminal should automatically close when the script finishes.

xeruf's user avatar

answered Jan 10, 2013 at 17:29

MDMoore313's user avatar

MDMoore313MDMoore313

5,9861 gold badge27 silver badges31 bronze badges

7

if you are in the same powershell you could do this:

Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript"

answered Nov 27, 2010 at 11:48

mjsr's user avatar

mjsrmjsr

6,4584 gold badges29 silver badges37 bronze badges

1

Since it’s sitting onto your desktop, I’d say the most effortless way to get this done is dragging it onto the elevation gadget.

Otherwise you could make a separate script using the elevate command on your ps1 script.

Or, you could apply elevate just to the service-starting bit.

answered Feb 12, 2010 at 22:02

badp's user avatar

badpbadp

3,6776 gold badges40 silver badges66 bronze badges

1

In addition to MDMoore313’s answer above:

If we want to execute the commands in the same working directory as we are currently in, we have to add a few things:

#### START ELEVATE TO ADMIN #####
param(
    [Parameter(Mandatory=$false)]
    [switch]$shouldAssumeToBeElevated,

    [Parameter(Mandatory=$false)]
    [String]$workingDirOverride
)

# If parameter is not set, we are propably in non-admin execution. We set it to the current working directory so that
#  the working directory of the elevated execution of this script is the current working directory
if(-not($PSBoundParameters.ContainsKey('workingDirOverride')))
{
    $workingDirOverride = (Get-Location).Path
}

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# If we are in a non-admin execution. Execute this script as admin
if ((Test-Admin) -eq $false)  {
    if ($shouldAssumeToBeElevated) {
        Write-Output "Elevating did not work :("

    } else {
        #                                                         vvvvv add `-noexit` here for better debugging vvvvv 
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -shouldAssumeToBeElevated -workingDirOverride "{1}"' -f ($myinvocation.MyCommand.Definition, "$workingDirOverride"))
    }
    exit
}

Set-Location "$workingDirOverride"
##### END ELEVATE TO ADMIN #####

# Add actual commands to be executed in elevated mode here:
Write-Output "I get executed in an admin PowerShell"

answered May 10, 2021 at 16:06

Jonas Taulien's user avatar

PowerShell ISE lives at %windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe. You can right-click that and select «Run as administrator» and run the script from in there.

You can also find it under the Windows Logo > All Programs > Accessories > Windows PowerShell and do the same thing with those shortcuts.

answered Jul 16, 2015 at 17:57

vapcguy's user avatar

If you want an option to launch a Powershell script as adminstrator, directly from the Explorer context-menu, see section 2 of my answer here: https://stackoverflow.com/a/57033941/2441655

answered Jul 15, 2019 at 4:56

Venryx's user avatar

VenryxVenryx

3162 silver badges8 bronze badges

sudo

Why does it have to take 30+ lines of code to do what 4 characters do?

So here, write a .bat file to invoke your script, in it use the:

Start-Process powershell.exe -Verb RunAs

answered Aug 23, 2022 at 8:46

Max's user avatar

The previous answers only tells you if the script is running from an admin. If starting the same script with elevated privileges, the user is still not admin.

A parameter which can be used to determine this is the following :

if (($myinvocation.UnboundArguments.Contains("-elevated")) -or ($testadmin -eq $true)) {
   #Good to go with Admin rights

} else {
    #Start with elevated privs

}

I’ve not been able to find a parameter that detects the Powershell environment has been started with Admin privileges.

answered Dec 22, 2022 at 14:05

JFH's user avatar

1

Add this to the beginning of the script:

$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}

answered Oct 23, 2017 at 20:34

Anthony's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

On my Windows 7 Desktop, I have script.ps1, which needs admin privileges (it starts a service). I want to click on this script and run it with admin privileges.

What’s the easiest way to accomplish this?

asked Feb 12, 2010 at 21:46

Sajee's user avatar

0

Here is one way of doing it, with the help of an additional icon on your desktop. I guess you could move the script someone else if you wanted to only have a single icon on your desktop.

  1. Create a shortcut to your Powershell script on your desktop
  2. Right-click the shortcut and click Properties
  3. Click the Shortcut tab
  4. Click Advanced
  5. Select Run as Administrator

You can now run the script elevated by simple double-clicking the new shortcut on your desktop.

answered Feb 13, 2010 at 12:58

Kez's user avatar

KezKez

16.6k15 gold badges67 silver badges94 bronze badges

6

On UAC-enabled systems, to make sure a script is running with full admin privileges, add this code at the beginning of your script:

param([switch]$Elevated)

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
    if ($elevated) {
        # tried to elevate, did not work, aborting
    } else {
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
    }
    exit
}

'running with full privileges'

Now, when running your script, it will call itself again and attempt to elevate privileges before running.
The -elevated switch prevents it from repeating if something fails.

You may remove the -noexit switch if the terminal should automatically close when the script finishes.

xeruf's user avatar

answered Jan 10, 2013 at 17:29

MDMoore313's user avatar

MDMoore313MDMoore313

5,9861 gold badge27 silver badges31 bronze badges

7

if you are in the same powershell you could do this:

Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript"

answered Nov 27, 2010 at 11:48

mjsr's user avatar

mjsrmjsr

6,4584 gold badges29 silver badges37 bronze badges

1

Since it’s sitting onto your desktop, I’d say the most effortless way to get this done is dragging it onto the elevation gadget.

Otherwise you could make a separate script using the elevate command on your ps1 script.

Or, you could apply elevate just to the service-starting bit.

answered Feb 12, 2010 at 22:02

badp's user avatar

badpbadp

3,6776 gold badges40 silver badges66 bronze badges

1

In addition to MDMoore313’s answer above:

If we want to execute the commands in the same working directory as we are currently in, we have to add a few things:

#### START ELEVATE TO ADMIN #####
param(
    [Parameter(Mandatory=$false)]
    [switch]$shouldAssumeToBeElevated,

    [Parameter(Mandatory=$false)]
    [String]$workingDirOverride
)

# If parameter is not set, we are propably in non-admin execution. We set it to the current working directory so that
#  the working directory of the elevated execution of this script is the current working directory
if(-not($PSBoundParameters.ContainsKey('workingDirOverride')))
{
    $workingDirOverride = (Get-Location).Path
}

function Test-Admin {
    $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
    $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

# If we are in a non-admin execution. Execute this script as admin
if ((Test-Admin) -eq $false)  {
    if ($shouldAssumeToBeElevated) {
        Write-Output "Elevating did not work :("

    } else {
        #                                                         vvvvv add `-noexit` here for better debugging vvvvv 
        Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -file "{0}" -shouldAssumeToBeElevated -workingDirOverride "{1}"' -f ($myinvocation.MyCommand.Definition, "$workingDirOverride"))
    }
    exit
}

Set-Location "$workingDirOverride"
##### END ELEVATE TO ADMIN #####

# Add actual commands to be executed in elevated mode here:
Write-Output "I get executed in an admin PowerShell"

answered May 10, 2021 at 16:06

Jonas Taulien's user avatar

PowerShell ISE lives at %windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe. You can right-click that and select «Run as administrator» and run the script from in there.

You can also find it under the Windows Logo > All Programs > Accessories > Windows PowerShell and do the same thing with those shortcuts.

answered Jul 16, 2015 at 17:57

vapcguy's user avatar

If you want an option to launch a Powershell script as adminstrator, directly from the Explorer context-menu, see section 2 of my answer here: https://stackoverflow.com/a/57033941/2441655

answered Jul 15, 2019 at 4:56

Venryx's user avatar

VenryxVenryx

3162 silver badges8 bronze badges

sudo

Why does it have to take 30+ lines of code to do what 4 characters do?

So here, write a .bat file to invoke your script, in it use the:

Start-Process powershell.exe -Verb RunAs

answered Aug 23, 2022 at 8:46

Max's user avatar

The previous answers only tells you if the script is running from an admin. If starting the same script with elevated privileges, the user is still not admin.

A parameter which can be used to determine this is the following :

if (($myinvocation.UnboundArguments.Contains("-elevated")) -or ($testadmin -eq $true)) {
   #Good to go with Admin rights

} else {
    #Start with elevated privs

}

I’ve not been able to find a parameter that detects the Powershell environment has been started with Admin privileges.

answered Dec 22, 2022 at 14:05

JFH's user avatar

1

Add this to the beginning of the script:

$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}

answered Oct 23, 2017 at 20:34

Anthony's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.


date30.09.2016

user

В Windows скрипты PowerShell (расширение .PS1) по умолчанию не ассоциированы с исполнимым файлом PowerShell.exe. При двойном щелке по файлу сценария PS1 открывается окно тестового редактора notepad.exe. Запустить файл PS1 на выполнение в среде PowerShell можно из контекстного меню проводника, выбрав пункт Run With PowerShell. Однако такой сценарий запускается в рамках сессии пользователя, без прав администратора. Хотя для тех же файлов скриптов .bat, .cmd, имеется отдельный пункт меню Run As administrator. В случае с PowerShell приходится открывать консоль Power Shell с повышенными правами и указывать полный путь к файлу скрипта. Не очень-то удобно.

Рассмотрим, как добавить в контекстное меню проводника File Explorer для файлов с расширением *.ps1, пункт, позволявший запустить скрипт PowerShell с правами администратора.

  1. Запустите редактор реестра (regedit.exe)
  2. Перейдите в ветку HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\shellHKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\shell
  3. Создайте подраздел с именем runas и перейдите в него
  4. Внутри раздела runas создайте пустой строковый параметр (String Value) с именем HasLUAShield (этот параметр добавит иконку UAC в контекстное меню проводника)
  5. В разделе runas создайте вложенный подраздел commandHasLUAShield
  6. В качестве значения параметра Default раздела command укажите значение:
    powershell.exe "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
    powershell.exe Command
  7. Теперь, если щелкнуть ПКМ по любому *.PS1 файлу, в контекстном меню можно выбрать пункт Run as administratorPowerShell скрипт ps1 - RunAsAdministrator

Совет. Если скрипт отрабатывает быстро, пользователь успевает только увидеть появившееся и быстро исчезнувшее окно PowerShell. А что делать, если результат выполнения скрипта должен остаться на экране для просмотра пользователем?

Чтобы после окончания работы скрипта, окно консоли PowerShell не закрывалось, необходимо добавить в строку параметр –NoExit:

powershell.exe –NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"





Some commands or tasks require elevation, meaning they must run in the context of an administrator. Such is true with PowerShell scripts, too. Running PowerShell scripts as an administrator means the PowerShell session must be elevated.

There are several ways to run PowerShell scripts as an administrator interactively and non-interactively—which is suitable for automation. We’ll cover them in this article, so stick around and enjoy.

Ways to Run PowerShell as Administrator (Interactive)

Running PowerShell scripts as an administrator requires an elevated PowerShell session. In most cases, doing so interactively is sufficient for users to run one-off or seldom-used scripts.

Here are the ways to interactively start PowerShell as an administrator so you can run your scripts and commands in God mode.

Note. These methods will trigger the UAC prompt to appear.

Windows Power User Menu

The Power User Menu is the quickest way to start PowerShell as an administrator.

Press Win+X on the keyboard or right-click the Start button to pull up the Power User Menu and click Windows PowerShell (Admin).

run powershell script as administrator

Note that on a Windows 11 computer, the Windows PowerShell (Admin) is replaced with Terminal (Admin) by default.

run powershell script as administrator without prompt

Run as Administrator Context Menu

The context menu (right-click pop-up menu) of executable files and their shortcuts include the Run as administrator context menu. This means you can right-click and select Run as administrator whenever you see the Windows PowerShell or PowerShell icon. Here are some examples:

Create a PowerShell Shortcut with Run as Administrator Enabled

You can also create a shortcut to run PowerShell as administrator.

  1. Right-click anywhere on the desktop and click New → Shortcut.
    run powershell script as admin
  2. Type powershell.exe (Windows PowerShell) or pwsh.exe (PowerShell 7+) and click Next.
    cmd run powershell script as administrator
  3. Type the shortcut name and click Finish.
    task scheduler run powershell script as administrator
  4. Right-click the new shortcut and click Properties.
    powershell run as administrator script
  5. Click Advanced on the Properties window. Check the “Run as administrator” box and click OKOK.
    powershell run script as administrator

Every time you launch PowerShell using the new shortcut, it will run as administrator.

Start PowerShell as Administrator from CMD

Another way to run PowerShell as administrator is by invoking it from the command line or as a CMD script.

From the CMD prompt, run one of the following commands to run Windows PowerShell or PowerShell Core:

REM Run Windows PowerShell as Admin 
PowerShell -Command "& {Start-Process powershell -Verb RunAs}"

REM Run PowerShell Core as Admin
Pwsh -Command "& {Start-Process Pwsh -Verb RunAs}"

run powershell script as administrator from command line

You can also create a CMD script using these commands. Open Notepad, paste one of the previous commands, and save it as a CMD file.

powershell run script as admin

You can then run PowerShell as administrator by double-clicking on the CMD file.

powershell script run as admin

Start a PowerShell Instance in Task Manager

The Task Manager is a high-privilege process that requires elevation. This means that when opening the Task Manager, the UAC prompt appears.

how to run a powershell script as admin

But once you’re in Task Manager, you can run PowerShell as administrator from it, and it will no longer trigger the UAC prompt.

  1. On the Task Manager window, click Run new task.
  2. Enter powershell.exe for Windows PowerShell or pwsh.exe for PowerShell Core.
  3. Check the “Create this task with administrative privileges” box and click OK.
    run script as administrator

Ways to Run PowerShell as Administrator (Non-Interactive)

What if you must run a PowerShell script unattended with administrative privileges? Like, in an automation scenario, when a script must run without user intervention and the UAC prompt must be bypassed?

In this example, I’m using a script called “RunMeAsAdmin.ps1” with the following code. This script outputs a message indicating whether it is run as administrator.

if (([System.Security.Principal.WindowsPrincipal] [System.Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)){ 
"Run as admin - SUCCESSFUL"
}
else {
"Run as admin - FAILED"
}

Start-Sleep -Seconds 10

As a Task with the Highest Privileges Enabled in Task Scheduler,

The out-of-the-box solution to run PowerShell scripts with non-interactive administrative rights is adding a Task Scheduler entry. The scheduled task can be configured to run with the highest privileges without triggering the UAC prompt.

Related post. Run PowerShell Script with Task Scheduler.

  1. Open the Task Scheduler and click “Create a task.”
    run as administrator powershell script
  2. Under the General tab, configure the following:
    • The name is RunMeAsAdmin.
    • Select Run only when user is logged on.
    • Check Run with highest privileges.
    • Configure for your operating system version (eg. Windows 10 or Windows Server 2022).
      how to run ps1 file as admin
  3. Switch to the Actions tab and click New.
    run powershell script as administrator from cmd
  4. In the New Action window:
    • Type powershell.exe for Windows PowerShell or pwsh.exe for PowerShell Core in the “Program/script” box.
    • Type -file “path_to_script” inside the “Add arguments” box where path_to_script is the full path of your script.
    • Click OK to close the New Action window.
      run ps1 file as administratorOptionally, you can add a scheduled trigger if needed. But we’ll skip this step for this example.
  5. Click OK to save the new task.
    run powershell script from cmd as administrator
  6. Once the task is created, select it from the list and click Run in the Actions pane.
    powershell script as administrator
  7. Or you can trigger it from PowerShell by running the below command:
    Start-ScheduledTask -TaskName <task name>

As you can see below, the task is triggered in a non-administrator PowerShell session, and the script runs in an Administrator session.

how to run script in powershell as admin

Related. List, Add, Edit, and Delete Scheduled Tasks with PowerShell.

Run PowerShell Scripts in an Automation Server (CI/CD)

A better solution to run PowerShell scripts with administrator privileges is through automation servers or CI/CD solutions. One example is Jenkins with the PowerShell plugin.

This article does not cover the Jenkins installation and configuration. For more information, refer to How to Install Jenkins with Let’s Encrypt SSL Certificate on Windows.

Suppose you have Jenkins. You can create a new Freestyle project. In this example, I’ll name it Run Me As Admin.

how to run ps1 as admin

Add a PowerShell step under Build Steps, paste the script, and click Save.

how to run powershell script as administrator

Once the project is created, you will see it on the dashboard. Click the Build Now button to trigger the build (run the PowerShell script.)

execute powershell script as administrator

After the build, click the build number under the Build History and select Console Output.

run .ps1 as admin

Review the console output; you should see a similar result to the one below.

powershell run script as administrator without prompt

Conclusion

Running PowerShell scripts as an administrator is optional, but knowing it is possible when necessary is good. The methods we explored in this tutorial produced the same results but exhibited different behaviors or user experiences, especially in systems where UAC is turned on.

Solutions to running PowerShell scripts as an administrator that bypasses the UAC prompt are also available. For automation purposes or without user intervention, you can use the built-in Task Scheduler to run PowerShell script with elevated privileges.

Third-party automation servers are also excellent for running PowerShell scripts as an administrator, such as Jenkins, which we briefly demonstrated.

kardashevsky cyril

Cyril Kardashevsky

I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.

I wanted a more enhanced version so I ended up with a module which allows:
UAC request if needed, printing and logging from nonprivileged instance (uses ipc and a network port) and some other candies. usage is just insert elevateme() in your script: in nonprivileged it listen for privileged print/logs and then exits returning false, in privileged instance it returns true immediately.
Supports pyinstaller.

prototype:

# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):

winadmin.py

#!/usr/bin/env python
# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4

# (C) COPYRIGHT © Preston Landers 2010
# (C) COPYRIGHT © Matteo Azzali 2020
# Released under the same license as Python 2.6.5/3.7


import sys, os
from traceback import print_exc
from multiprocessing.connection import Listener, Client
import win32event #win32com.shell.shell, win32process
import builtins as __builtin__ # python3

# debug suffixes for remote printing
dbz=["","","",""] #["J:","K:", "G:", "D:"]
LOGTAG="LOGME:"

wrconn = None


#fake logger for message sending
class fakelogger:
    def __init__(self, xlogger=None):
        self.lg = xlogger
    def write(self, a):
        global wrconn
        if wrconn is not None:
            wrconn.send(LOGTAG+a)
        elif self.lg is not None:
            self.lg.write(a)
        else:
            print(LOGTAG+a)
        

class Writer():
    wzconn=None
    counter = 0
    def __init__(self, tport=6000,authkey=b'secret password'):
        global wrconn
        if wrconn is None:
            address = ('localhost', tport)
            try:
                wrconn = Client(address, authkey=authkey)
            except:
                wrconn = None
            wzconn = wrconn
            self.wrconn = wrconn
        self.__class__.counter+=1
        
    def __del__(self):
        self.__class__.counter-=1
        if self.__class__.counter == 0 and wrconn is not None:
            import time
            time.sleep(0.1) # slows deletion but is enough to print stderr
            wrconn.send('close')
            wrconn.close()
    
    def sendx(cls, mesg):
        cls.wzconn.send(msg)
        
    def sendw(self, mesg):
        self.wrconn.send(msg)
        

#fake file to be passed as stdout and stderr
class connFile():
    def __init__(self, thekind="out", tport=6000):
        self.cnt = 0
        self.old=""
        self.vg=Writer(tport)
        if thekind == "out":
            self.kind=sys.__stdout__
        else:
            self.kind=sys.__stderr__
        
    def write(self, *args, **kwargs):
        global wrconn
        global dbz
        from io import StringIO # # Python2 use: from cStringIO import StringIO
        mystdout = StringIO()
        self.cnt+=1
        __builtin__.print(*args, **kwargs, file=mystdout, end = '')
        
        #handles "\n" wherever it is, however usually is or string or \n
        if "\n" not in mystdout.getvalue():
            if mystdout.getvalue() != "\n":
                #__builtin__.print("A:",mystdout.getvalue(), file=self.kind, end='')
                self.old += mystdout.getvalue()
            else:
                #__builtin__.print("B:",mystdout.getvalue(), file=self.kind, end='')
                if wrconn is not None:
                    wrconn.send(dbz[1]+self.old)
                else:
                    __builtin__.print(dbz[2]+self.old+ mystdout.getvalue(), file=self.kind, end='')
                    self.kind.flush()
                self.old=""
        else:
                vv = mystdout.getvalue().split("\n")
                #__builtin__.print("V:",vv, file=self.kind, end='')
                for el in vv[:-1]:
                    if wrconn is not None:
                        wrconn.send(dbz[0]+self.old+el)
                        self.old = ""
                    else:
                        __builtin__.print(dbz[3]+self.old+ el+"\n", file=self.kind, end='')
                        self.kind.flush()
                        self.old=""
                self.old=vv[-1]

    def open(self):
        pass
    def close(self):
        pass
    def flush(self):
        pass
        
        
def isUserAdmin():
    if os.name == 'nt':
        import ctypes
        # WARNING: requires Windows XP SP2 or higher!
        try:
            return ctypes.windll.shell32.IsUserAnAdmin()
        except:
            traceback.print_exc()
            print ("Admin check failed, assuming not an admin.")
            return False
    elif os.name == 'posix':
        # Check for root on Posix
        return os.getuid() == 0
    else:
        print("Unsupported operating system for this module: %s" % (os.name,))
        exit()
        #raise (RuntimeError, "Unsupported operating system for this module: %s" % (os.name,))

def runAsAdmin(cmdLine=None, wait=True, hidden=False):

    if os.name != 'nt':
        raise (RuntimeError, "This function is only implemented on Windows.")

    import win32api, win32con, win32process
    from win32com.shell.shell import ShellExecuteEx

    python_exe = sys.executable
    arb=""
    if cmdLine is None:
        cmdLine = [python_exe] + sys.argv
    elif not isinstance(cmdLine, (tuple, list)):
        if isinstance(cmdLine, (str)):
            arb=cmdLine
            cmdLine = [python_exe] + sys.argv
            print("original user", arb)
        else:
            raise( ValueError, "cmdLine is not a sequence.")
    cmd = '"%s"' % (cmdLine[0],)

    params = " ".join(['"%s"' % (x,) for x in cmdLine[1:]])
    if len(arb) > 0:
        params += " "+arb
    cmdDir = ''
    if hidden:
        showCmd = win32con.SW_HIDE
    else:
        showCmd = win32con.SW_SHOWNORMAL
    lpVerb = 'runas'  # causes UAC elevation prompt.

    # print "Running", cmd, params

    # ShellExecute() doesn't seem to allow us to fetch the PID or handle
    # of the process, so we can't get anything useful from it. Therefore
    # the more complex ShellExecuteEx() must be used.

    # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd)

    procInfo = ShellExecuteEx(nShow=showCmd,
                              fMask=64,
                              lpVerb=lpVerb,
                              lpFile=cmd,
                              lpParameters=params)

    if wait:
        procHandle = procInfo['hProcess']    
        obj = win32event.WaitForSingleObject(procHandle, win32event.INFINITE)
        rc = win32process.GetExitCodeProcess(procHandle)
        #print "Process handle %s returned code %s" % (procHandle, rc)
    else:
        rc = procInfo['hProcess']

    return rc


# xlogger : a logger in the server/nonprivileged script
# tport : open port of communication, 0 for no comm [printf in nonprivileged window or silent]
# redir : redirect stdout and stderr from privileged instance
#errFile : redirect stderr to file from privileged instance
def elevateme(xlogger=None, tport=6000, redir=True, errFile=False):
    global dbz
    if not isUserAdmin():
        print ("You're not an admin.", os.getpid(), "params: ", sys.argv)

        import getpass
        uname = getpass.getuser()
        
        if (tport> 0):
            address = ('localhost', tport)     # family is deduced to be 'AF_INET'
            listener = Listener(address, authkey=b'secret password')
        rc = runAsAdmin(uname, wait=False, hidden=True)
        if (tport> 0):
            hr = win32event.WaitForSingleObject(rc, 40)
            conn = listener.accept()
            print ('connection accepted from', listener.last_accepted)
            sys.stdout.flush()
            while True:
                msg = conn.recv()
                # do something with msg
                if msg == 'close':
                    conn.close()
                    break
                else:
                    if msg.startswith(dbz[0]+LOGTAG):
                        if xlogger != None:
                            xlogger.write(msg[len(LOGTAG):])
                        else:
                            print("Missing a logger")
                    else:
                        print(msg)
                    sys.stdout.flush()
            listener.close()
        else: #no port connection, its silent
            WaitForSingleObject(rc, INFINITE);
        return False
    else:
        #redirect prints stdout on  master, errors in error.txt
        print("HIADM")
        sys.stdout.flush()
        if (tport > 0) and (redir):
            vox= connFile(tport=tport)
            sys.stdout=vox
            if not errFile:
                sys.stderr=vox
            else:
                vfrs=open("errFile.txt","w")
                sys.stderr=vfrs
            
            #print("HI ADMIN")
        return True


def test():
    rc = 0
    if not isUserAdmin():
        print ("You're not an admin.", os.getpid(), "params: ", sys.argv)
        sys.stdout.flush()
        #rc = runAsAdmin(["c:\\Windows\\notepad.exe"])
        rc = runAsAdmin()
    else:
        print ("You are an admin!", os.getpid(), "params: ", sys.argv)
        rc = 0
    x = raw_input('Press Enter to exit.')
    return rc
    
if __name__ == "__main__":
    sys.exit(test())

  • Запустить службу hyper v windows 10
  • Заставка при блокировке windows 10
  • Заставка на режим ожидания windows 10
  • Запустить скайп на windows 7
  • Зарядка не выполняется windows 10 ноутбук hp