none
Create and Run a Task from an Administrator Command Prompt To Run As Administrator At Startup ( Boot ) RRS feed

  • Question

  • I would like to perform something incredibly simple which does not seem to work.

     

    An application must be run as administrator or else this application will not run and work.

     

    Logically, one has to schedule a task from a command prompt which is run as administrator to be able to run or schedule a task to be run as administrator.

     

    I have tried to use Schtasks. When Schtasks is run, everything is OK and a new task with the given name is created in System32\Tasks. However, the task is not run.

     

    I have tried :

     

    schtasks /Create /RU SYSTEM /SC ONLOGON /TN SomeRandomName /TR FullPathAndNameOfTheApplication /RL HIGHEST /F

     

    schtasks /Create /RU administrator /SC ONLOGON /TN SomeRandomName /TR FullPathAndNameOfTheApplication /RL HIGHEST /F

     

    Neither of these works.

     

    I have also tried the standard way which VB.NET provides :

     

    My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, Application.ExecutablePath)

     

    This works perfectly BUT only for applications which do not run as administrator and cannot run an application as administrator. I WILL BE PERFECTLY HAPPY to use this way provided there is a way to ask the user to provide administrator privileges FROM WITHIN THE APPLICATION OR BEFORE THE APPLICATION RUNS as is possible in Android. However, I have not be able to find any information on how to do this in Windows 10 and other versions.

     

    I would be happy to be informed of ALL possibilities to schedule a task which must be run as administrator when the computer starts.

     

    Have not tried to run a process from within with runas to see whether Windows would as for an administrator yet. 

     

    Sunday, October 29, 2017 2:54 AM

All replies

  •  Does the path or filename of your "FullPathAndNameOfTheApplication" have any spaces in it anywhere?  If it does,  you need to surround it with a backslash and quote as said in This Link.  I ran into this problem myself recently.  The task gets created but,  never runs.  If you look in the Task Scheduler and it says the file could not be found and you have spaces in your path or filename,  this is likely to be the problem or one of your problems.  For example,  note the  \"  characters at the start and end of the full file path...

    /tr "\"C:\Some Folder\Another Folder\My Program.exe"\" 

     Also,  if your exe, bat, or other file that the task runs needs to let the user interact with it,  then the \ru should not be set to SYSTEM.  Below is quoted from the Command Line Args For Schtasks in the "To schedule a task that runs with system permissions" section...

    "The System account does not have interactive logon rights. Users cannot see or interact with programs or tasks run with system permissions."  

     You may also want to look through this link too.  -->  Schtasks.exe

     Here is a working example that i just tested and it runs my "Get Restore Points" program which requires administrator rights to run.

    Public Class Form1
    
        'This application must be run as administrator to create the task
    
        Private Sub Button_CreateTask_Click(sender As Object, e As EventArgs) Handles Button_CreateTask.Click
            Dim p As New Process
            With p.StartInfo
                .FileName = "schtasks.exe"
                .Arguments = "/create /tn " & Chr(34) & "Logon Task example" & Chr(34) & " /tr " & Chr(34) & "\" & Chr(34) & "C:\TestFolder\My Scheduled Tasks\Get Restore Points.exe" & Chr(34) & "\" & Chr(34) & " /sc onlogon /ru " & Chr(34) & Environment.UserDomainName & "\" & Environment.UserName & Chr(34) & " /rl highest"
                .UseShellExecute = False
                .RedirectStandardOutput = True
                .CreateNoWindow = True
            End With
            p.Start()
    
            Dim s As String = p.StandardOutput.ReadToEnd
            MessageBox.Show(s, "Create Task Results..")
        End Sub
    
    End Class
    


    If you say it can`t be done then i`ll try it

    • Edited by IronRazerz Monday, October 30, 2017 1:05 AM Fixed Code Example
    Sunday, October 29, 2017 10:37 PM
  • SO FAR :

     

    I have been able to solve the problem BUT I still ask for any other solutions, probably, much better and more elegant than the one I have found, which is :

     

    1. To register a task which is to be run at start up from within the code, use :

     

    My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, Application.ExecutablePath)

     

    To unregister the task, use :

     

    My.Computer.Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).DeleteValue(Application.ProductName)

     

    2. To ensure the application is run as administrator either when automatically run at start up or when manually double clicked upon to run, use this IMMEDIATELLY AT THE VERY START OF THE CODE AFTER FORM.LOAD() :

     

    'Check for Administrator

            Dim boolExceptionCaught As Boolean = False

            Dim identity = WindowsIdentity.GetCurrent()

            Dim principal = New WindowsPrincipal(identity)

            isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator)

            If isElevated = False Then

                boolInitialClose = True

                ProcessLaunch.StartInfo.Verb = "runas" ' ( ExePathRunAs ) Run as Administrator.

                ProcessLaunch.StartInfo.FileName = Application.ExecutablePath()

                Try

                    ProcessLaunch.Start()

                Catch objExeptionWin32 As System.ComponentModel.Win32Exception

                    boolExceptionCaught = True

                    ProcessLaunch.Close()

                    Close()

                Finally

                    If boolExceptionCaught = False Then

                        ProcessLaunch.Close()

                        Close()

                    End If

                End Try

                Exit Sub

          End If

      

    PLEASE, NOTE : the use of the CLASS VARIBLE ( consider global for the class form1 ) boolInitialClose ( Dim boolInitialClose As Boolean = False ) is not necessary for the discussed question. I need this for MyBase.Closing() to avoid some action there which is not desirable when the application is initially abruptly closed because of the lack of administrator level.

     

    PLEASE, NOTE : This method seems to work, yet, at start up, Windows asks for administrator approval ( UAE ). Logically, there should be the way to tell Windows not to ask FROM ADMINISTRATOR LEVEL RUN. I have not been able to find a reliable one, yet, I am not concerned at all and I even prefer the user to have more notifications of applications which require administrator.

     

    Again, the solution works but is not elegant.

     

    PLEASE, NOTE : Ensure the application is ENABLED in the start up bar of Task Manager. Previous disable’s are remembered. Thus, manually check the start up bar of Task Manager before Windows is restarted to check the automatic start at start up of the application.

     


    In order to ensure the blanks are allowed in ProcessLaunch.StartInfo.FileName, I have just tested : ProcessLaunch.StartInfo.FileName = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe" The quotes are for VB to denote a string and are not part of the string. This test seems to have worked OK and Adobe opened although there are a lot of blanks in the path. DOES ANYONE HAVE ANYTHING TO ADD TO THE CASE WHEN StartInfo.FileName CONTAINS A FILE PATH WITH BLANKS AND THE PROCESS DOES NOT HAVE ANY PARAMETERS?

     

    Monday, October 30, 2017 2:20 AM
  • Thanks. Your answer is excellent. However, please, be kind to see the reply I have just posted there. 

     

    Thanks. 

     

    Monday, October 30, 2017 2:28 AM
  • Thanks for the excellent answer. 

     

    No, I do not have blanks in the path and name of the executable neither do I have any blanks in the random name of the task ( in your example : Logon Task example ).  

     

    Thank you for the SYSTEM and user interface. I did not use SYSTEM as /RU before but, after so many attempts, I decided to check to see what happened. 

     

    I CAN SEE YOU USE Environment.UserDomainName Environment.UserName ( IN DOUBLE QUOTES " ( Chr(34) ).

     

    I think this does the trick as someone else suggested a solution alike. 

     

    I am afraid to use schtasks as I am not very happy with the reliability of this way. However, I do want to know how because I may not have any other choice. Thus, I want to ask you to clarify what exactly makes your way work. This is also good for other people to read. 

     

    So far you said : 

     

    1. SYSTEM must not be used as /RU because systems tasks do not allow user interaction. 

    2. Best always surround every name with double quotes. The user may install the application in folder which have blanks in the name. 

    3. Looks like /RU must be Environment.UserDomainName Environment.UserName    in the way you suggested. Can you please, confirm and comment on whether this is the MAIN trick to schedule a task to run as administrator from an application which runs as administrator. Please, be kind to provide some more input here.

    4. Use /SC ONSTART and nothing else in this case. 

    5. Read Schtasks /Create /? and, probably, Schtasks /Delete /? 

     

    Monday, October 30, 2017 2:48 AM
  •  There really is not any great wealth of detailed information on doing this that i have found other than the links i have already given you in my prior post.  About all i can suggest is doing the same thing i did,  read through all those links and pay attention to what command switches each example of interest uses.  Then see what info they give for the switches in the command line args link.  Then test, test, test....  until you get it right.

     I don't know for sure if the domain name is really necessary unless you are creating a task on a remote computer but,  it does not seem to hurt doing it on the local computer as i did.  I was using it like that when i found my solution and just never went back to test if it worked without it.

     I would also suggest doing your testing in the command prompt (run as administrator) so you can see any errors that my example will not show you.  Mine only shows a Success message but,  will show a blank messagebox if an error occurs or it needs to prompt for a password.

     If you know your administrator name and password,  you can supply the password too with the /rp switch.  As i said,  test, test, test.  It should be reliable when you get the correct set of switches and arguments set up right.  It takes time and lots of patients.   8)

    PS:  If you have created the app that the task runs, then you can try this.... Change that application's app.manifest to require administrator rights so it will prompt for administrator name and/or password when it is ran.  Then just create a standard task without using the /ru, /rp,  and  /rl  switches.  I'm not sure if it would work for you though?


    If you say it can`t be done then i`ll try it

    Monday, October 30, 2017 1:50 PM
  • If the OP intends to run a program using an account that is a member of the Administrator's group at system startup (i.e., before any user has logged on)  then it will run in session 0 which is not interactive.  Anything that uses UI to request a password will hang.
    Monday, October 30, 2017 1:54 PM
  • If the OP intends to run a program using an account that is a member of the Administrator's group at system startup (i.e., before any user has logged on)  then it will run in session 0 which is not interactive.  Anything that uses UI to request a password will hang.

     OP seems to have been using the "ONLOGON" schedule,  which made me believe they wanted it to run on logon.  However,  your info is true.  8)

    If you say it can`t be done then i`ll try it

    Monday, October 30, 2017 2:05 PM
  •  OP seems to have been using the "ONLOGON" schedule,  which made me believe they wanted it to run on logon.  However,  your info is true.  8)

    And the use of ONLOGON instead of ONSTART is one of the issues that is preventing schtasks.exe from creating the desired startup task per the initial question. I covered this in the response I posted to the duplicated thread in the other forum.
    Monday, October 30, 2017 2:14 PM
  • And the use of ONLOGON instead of ONSTART is one of the issues that is preventing schtasks.exe from creating the desired startup task per the initial question. I covered this in the response I posted to the duplicated thread in the other forum.
     Hmmm...  i did not notice that it was the same person's question in that other thread you linked to.  I guess i did not understand OP wanted it to run on startup instead of on logon.  I guess that is what i get from just going off OP's posted code and not asking for more details.

    If you say it can`t be done then i`ll try it

    Monday, October 30, 2017 2:28 PM
  • I would summarise better after an answer in another place in the forum for whomever wants to use schtasks : 

     

    1. SYSTEM must not be used as /RU because systems tasks do not allow user interaction. 

    2. Best always surround every name with double quotes. The user may install the application in folder which have blanks in the name. 

    3. /RU must be Environment.UserDomainName Environment.UserName  

    4. Use /SC ONSTART and nothing else in this case. 

    5. Read Schtasks /Create /? and, probably, Schtasks /Delete /? 

     

    Tuesday, October 31, 2017 3:33 AM
  • If your question about how to use schtatsks.exe to create a scheduled task to run at startup has been resolved kindly mark the answers to close the thread.
    • Edited by RLWA32 Tuesday, October 31, 2017 11:03 AM
    Tuesday, October 31, 2017 11:02 AM
  • Steven,

    Have you any idea why they did that at Microsoft (and other OS makers). 

    As I understand you, it is stupid of them and it would be good as everybody could see in this forum how everybody can simply process any program you want with removing those unnecessary administrator rights. 


    Success
    Cor


    Tuesday, October 31, 2017 11:08 AM
  • No. This is not true. 

     

    Everyone must be allowed to make software which uses stuff which requires to run as administrator. Everything which the system gives is for everyone and not only for some and everyone can use everything as they want. 

     

    Usually, people would see the message which asks for administrator and decide what to do. Thus, the correct approach would be similar to Android : simply ask for permission wherever in the code and once the permission is given, continue. There is something automatic alike in Windows but I am not sure how well this works : Windows asks for administrator only when the code hits a feature which requires such. 

     

    Therefore, everyone must know how to run programs as administrator regardless of the consequences. The benefits to do so outweigh the misuse for which there are not very many possibilities anyways. Also, the designers of the OS just want to cover themselves against possible blames and thus do things which are against the user, an approach typical for every aspect of human activity : people do not work, they keep themselves from trouble instead, which trouble is either not there or is so remote, the probability for something to happen is either almost zero or negligible. 

     

     

    Thursday, November 2, 2017 7:30 AM
  • Thanks for the answer. I think the designers of schtasks have the inability to explain themselves. Probably considered as a side design which is not important. 

     

    I have previously tried the manifest approach, yet, Windows store may not allow a manifest which requires administrator. 

     

    Thursday, November 2, 2017 7:44 AM
  • I am sorry to intervene in your discussion BUT all they had to do is to allow a task to run either before logon ( startup ) or after logon. As long as the administrator rights are granted by a Windows run window which will allow user input and as long as the task has been SCHEDULED FROM AN ADMINISTRATOR LEVEL, then the task should be fully executed with a full GUI either after all other system startups and before logon or after logon. 

     

    The idea to run a task before logon is obvious. The idea to run after logon would allow the system to do whatever work is necessary undisturbed and only after logon, where the system work is not as important as before the logon, the system can run the task after all other system tasks as well. Some tasks require to be run before logon, most do not. 

     

    Generally, the idea to run a task after logon is to run the task exactly the same as the user would when right clicks on the task and clicks run as administrator. Just automates the human clicks. Whenever the user does not have administrator privileges, the Window which asks for administrator approval will not run at all and either a notification will be displayed to say the user does not have the level or a window which asks for a password. 

     

    Thus ONSTART and ONLOGON should have only one difference : ONSTART starts the task just before the window which asks for password to log on the computer ( which DOES have UI as the password has to be entered and the mouse works as well to initiate the process and allow the user to use the mouse for the password navigation ), ONLOGON waits for the whole logon to take place and runs the task thereafter when the user is allowed access to the PC ( Desktop, Files, etcetera ). 

     

    Thursday, November 2, 2017 7:58 AM