Archive

Posts Tagged ‘Run As Admin’

Get AutoHotkey To Interact With Admin Windows Without Running AHK Script As Admin

November 21st, 2013 6 comments

A while back I posted about AutoHotkey not being able to interact with Windows 8 windows and other applications that were Ran As Admin.  My solution was to run your AutoHotkey (AHK) script as admin as well, and I also showed how to have your AHK script start automatically with Windows, but not as an admin.  Afterwards I followed that up with a post about how to get your AHK script to run as admin on startup, so life was much better, but still not perfect.UAC Never Notify

 

Problems with running your AHK script as admin

  1. You may have to deal with the annoying UAC prompt every time you launch your script.
  2. Any programs the script launches also receive administrative privileges.

#1 is only a problem if you haven’t set your AHK script to run as admin on startup as I showed in my other blog post (i.e. you are still manually launching your script) or you haven’t changed your UAC settings to never prompt you with notifications (which some companies restrict) (see screenshot to the right).

#2 was a problem for me. I use AHK Command Picker every day. A lot. I’m a developer and in order for Visual Studio to interact with IIS it requires admin privileges, which meant that if I wanted to be able to use AHK Command Picker in Visual Studio, I had to run it as admin as well.  The problem for me was that I use AHK Command Picker to launch almost all of my applications, which meant that most of my apps were now also running as an administrator.  For the most part this was fine, but there were a couple programs that gave me problems running as admin. E.g. With PowerShell ISE when I double clicked on a PowerShell file to edit it, instead of opening in the current (admin) ISE instance, it would open a new ISE instance.

    There is a solution

    Today I stumbled across this post on the AHK community forums.  Lexikos has provided an AHK script that will digitally sign the AutoHotkey executable, allowing it to interact with applications running as admin, even when your AHK script isn’t.

    Running his script is pretty straight forward:

    1. Download and unzip his EnableUIAccess.zip file.
    2. Double-click the EnableUIAccess.ahk script to run it, and it will automatically prompt you.
    3. Read the disclaimer and click OK.
    4. On the Select Source File prompt choose the C:\Program Files\AutoHotkey\AutoHotkey.exe file.  This was already selected by default for me. (Might be Program Files (x86) if you have 32-bit AHK installed on 64-bit Windows)
    5. On the Select Destination File prompt choose the same C:\Program Files\AutoHotkey\AutoHotkey.exe file again.  Again, this was already selected by default for me.
    6. Click Yes to replace the existing file.
    7. Click Yes when prompted to Run With UI Access.

    That’s it.  (Re)Start your AHK scripts and they should now be able to interact with Windows 8 windows and applications running as admin 🙂

    This is a great solution if you want your AHK script to interact with admin windows, but don’t want to run your script as an admin.

     

    Did you know

    If you do want to launch an application as admin, but don’t want to run your AHK script as admin, you can use the RunAs command.

     

    I hope you found this article useful.  Feel free to leave a comment.

    Happy coding!

    Provide A Batch File To Run Your PowerShell Script From; Your Users Will Love You For It

    November 16th, 2013 82 comments

    A while ago in one of my older posts I included a little gem that I think deserves it’s own dedicated post; calling PowerShell scripts from a batch file.

    Why call my PowerShell script from a batch file?

    When I am writing a script for other people to use (in my organization, or for the general public) or even for myself sometimes, I will often include a simple batch file (i.e. *.bat or *.cmd file) that just simply calls my PowerShell script and then exits.  I do this because even though PowerShell is awesome, not everybody knows what it is or how to use it; non-technical folks obviously, but even many of the technical folks in our organization have never used PowerShell.

    Let’s list the problems with sending somebody the PowerShell script alone; The first two points below are hurdles that every user stumbles over the first time they encounter PowerShell (they are there for security purposes):

    1. When you double-click a PowerShell script (*.ps1 file) the default action is often to open it up in an editor, not to run it (you can change this for your PC).
    2. When you do figure out you need to right-click the .ps1 file and choose Open With –> Windows PowerShell to run the script, it will fail with a warning saying that the execution policy is currently configured to not allow scripts to be ran.
    3. My script may require admin privileges in order to run correctly, and it can be tricky to run a PowerShell script as admin without going into a PowerShell console and running the script from there, which a lot of people won’t know how to do.
    4. A potential problem that could affect PowerShell Pros is that it’s possible for them to have variables or other settings set in their PowerShell profile that could cause my script to not perform correctly; this is pretty unlikely, but still a possibility.
        So imagine you’ve written a PowerShell script that you want your grandma to run (or an HR employee, or an executive, or your teenage daughter, etc.). Do you think they’re going to be able to do it?  Maybe, maybe not.

    You should be kind to your users and provide a batch file to call your PowerShell script.

    The beauty of batch file scripts is that by default the script is ran when it is double-clicked (solves problem #1), and all of the other problems can be overcome by using a few arguments in our batch file.

    Ok, I see your point. So how do I call my PowerShell script from a batch file?

    First, the code I provide assumes that the batch file and PowerShell script are in the same directory.  So if you have a PowerShell script called “MyPowerShellScript.ps1” and a batch file called “RunMyPowerShellScript.cmd”, this is what the batch file would contain:

    @ECHO OFF
    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'";
    

    Line 1 just prevents the contents of the batch file from being printed to the command prompt (so it’s optional).  Line 2 gets the directory that the batch file is in.  Line 3 just appends the PowerShell script filename to the script directory to get the full path to the PowerShell script file, so this is the only line you would need to modify; replace MyPowerShellScript.ps1 with your PowerShell script’s filename.  The 4th line is the one that actually calls the PowerShell script and contains the magic.

    The –NoProfile switch solves problem #4 above, and the –ExecutionPolicy Bypass argument solves problem #2.  But that still leaves problem #3 above, right?

    Call your PowerShell script from a batch file with Administrative permissions (i.e. Run As Admin)

    If your PowerShell script needs to be run as an admin for whatever reason, the 4th line of the batch file will need to change a bit:

    @ECHO OFF
    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";
    

    We can’t call the PowerShell script as admin from the command prompt, but we can from PowerShell; so we essentially start a new PowerShell session, and then have that session call the PowerShell script using the –Verb RunAs argument to specify that the script should be run as an administrator.

    And voila, that’s it.  Now all anybody has to do to run your PowerShell script is double-click the batch file; something that even your grandma can do (well, hopefully).  So will your users really love you for this; well, no.  Instead they just won’t be cursing you for sending them a script that they can’t figure out how to run.  It’s one of those things that nobody notices until it doesn’t work.

    So take the extra 10 seconds to create a batch file and copy/paste the above text into it; it’ll save you time in the long run when you don’t have to repeat to all your users the specific instructions they need to follow to run your PowerShell script.

    I typically use this trick for myself too when my script requires admin rights, as it just makes running the script faster and easier.

    Bonus

    One more tidbit that I often include at the end of my PowerShell scripts is the following code:

    # If running in the console, wait for input before closing.
    if ($Host.Name -eq "ConsoleHost")
    { 
    	Write-Host "Press any key to continue..."
    	$Host.UI.RawUI.FlushInputBuffer()	# Make sure buffered input doesn't "press a key" and skip the ReadKey().
    	$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
    }
    

    This will prompt the user for keyboard input before closing the PowerShell console window.  This is useful because it allows users to read any errors that your PowerShell script may have thrown before the window closes, or even just so they can see the “Everything completed successfully” message that your script spits out so they know that it ran correctly.  Related side note: you can change your PC to always leave the PowerShell console window open after running a script, if that is your preference.

    I hope you find this useful.  Feel free to leave comments.

    Happy coding!

    Update

    Several people have left comments asking how to pass parameters into the PowerShell script from the batch file.

    Here is how to pass in ordered parameters:

    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%' 'First Param Value' 'Second Param Value'";
    

    And here is how to pass in named parameters:

    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%' -Param1Name 'Param 1 Value' -Param2Name 'Param 2 Value'"
    

    And if you are running the admin version of the script, here is how to pass in ordered parameters:

    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"First Param Value"""" """"Second Param Value"""" ' -Verb RunAs}"
    
    And here is how to pass in named parameters:
    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" -Param1Name """"Param 1 Value"""" -Param2Name """"Param 2 value"""" ' -Verb RunAs}";
    
    And yes, the PowerShell script name and parameters need to be wrapped in 4 double quotes in order to properly handle paths/values with spaces.

    Get AutoHotkey Script To Run As Admin At Startup

    November 6th, 2012 4 comments

    <Update>Before you go running your script as an admin, see if this less obtrusive fix will solve your problems.</Update>

    A few weeks back I posted some problems with running AutoHotkey (AHK) in Windows 8, and that the solution was to run your AHK script as admin.  I also showed how to have the script start automatically when you logged into Windows.  What I didn’t realize at the time though was that the method only worked for launching my AHK script as an admin because I had disabled UAC in the registry (which prevents most Metro apps from working in Windows 8, and likely isn’t acceptable for most people).

    So here is a Windows 8, UAC-friendly method to automatically launch your AHK scripts as admin at startup (also works in previous versions of Windows).  The trick is to use the Task Scheduler:

    1. Open the Task Scheduler (also known as “Schedule tasks” in Windows 8 Settings).

    Open Task Scheduler

    2. Create a new Basic Task.

    3. Give it a name and description (something like “launch AutoHotkey script at login”), and then specify to have it run “When I log on”.  Then specify that you want it to “Start a program”, and then point it towards your AutoHotkey script.  Before you finish the wizard, check off “Open the Properties dialog for this task when I click Finish”.

    Create Basic Task in Task Scheduler

    4. When that Properties dialog opens up, go to the Conditions tab and make sure none of the checkboxes under the Power category are checked off; this will ensure the script still launches if you are on a laptop and not plugged into AC power.

    Basic Task Conditions

    5. Now here is the important part; To have your script “Run as admin”, on the General tab check off “Run with highest privileges”.

    Run Scheduled Task as Admin_thumb[3]

    Now your AHK script should start automatically as soon as you log into Windows; even when UAC is enabled Smile

    6. If your AHK script uses an #Include statement to include other files, you may get an error similar to this one when your task runs:

    “#Include file … cannot be opened. The program will exit.”

    AHK Cannot Open Include File

    The solution to this is to tell your AHK script to start in the same directory as the file that you want to include.  So you will need to edit your scheduled task’s Action to specify the Start In directory.

    Task Scheduler Start In Directory

    Happy coding!

    ==< EDIT >==

    What I failed to realize earlier was that by default the Task Scheduler runs it’s programs in non-interactive mode, so they may run as the correct user, but in a different user session.  Since most AHK scripts are interactive (i.e. they respond to user input), this means that your script may not work exactly as it should all of the time.  For example, my AHK scripts were not able to launch ClickOnce applications.

    The fix is to create your Scheduled Task in interactive mode.  Unfortunately you cannot do this through the GUI; it must be done through the command line.  So if you open up a command prompt you can use the following command to create a new interactive scheduled task:

    schtasks /Create /RU "[Domain][Username]" /SC ONLOGON /TN "[Task Name]" /TR "[Path to program to run]" /IT /V1

    for example:

    schtasks /Create /RU "Dan Schroeder" /SC ONLOGON /TN "Launch AHK Command Picker" /TR "D:AHKStuffAHKCommandPicker.ahk" /IT /V1

    The /IT switch is what tells it to create the task in Interactive mode.  The /V1 switch actually specifies to create the task as a Windows XP/2000/Server 2003 compatible task, and has the added benefit of making the task run as admin by default with the Start In directory specified as the directory holding the file to run (i.e. steps 5 and 6 above; you will still need to do step 4 though).

    If you already have your Scheduled Task created, you can simply make it interactive with the command:

    schtasks /Change /TN “[Task Name]” /IT

    I hope you find this as helpful as I did!

    ==</ EDIT >==

    AutoHotkey cannot interact with Windows 8 Windows…or can it!

    September 10th, 2012 No comments

    <Update>Before you go running your script as an admin, see if this less obtrusive fix will solve your problems.</Update>

    If you’ve installed Windows 8 and are trying to use AutoHotkey (AHK) to interact with some of the Winodws 8 Windows (such as the Control Panel for example), or with apps that need to be Ran As Administrator, then you’ve likely become very frustrated as I did to discover that AHK can not send any commands (keyboard or mouse input) to these windows.  This was a huge concern as I often need to run Visual Studio as an administrator and wanted my hotkeys and hotstrings to work in Visual Studio.  After a day of fighting I finally realized the answer (and it’s pretty obvious once you think about it).  If you want AHK to be able to interact with Windows 8 Windows or apps running as administrator, then you also need to have your AHK script Run As Administrator.

    If you are like me then you probably have your AHK scripts set to run automatically at login, which means you don’t have the opportunity to right-click on the script and manually tell it to Run As Administrator.  Luckily the work around is simple.

    First, if you want to have your AHK script (or any program for that matter) run when you log in, create a shortcut to the application and place the shortcut in:

    C:\Users\[User Name]\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

    Note that you will need to replace “[User Name]” with your username, and that “AppData” is a hidden folder so you’ll need to turn on viewing hidden folders to see it (you can also type “shell:startup” in the Windows Explorer path to jump directly to this folder).  So by placing that shortcut there Windows will automatically run your script when you log on.  Now, to get it to run as an administrator by default, right-click on the shortcut and go to Properties.  Under the Shortcut tab, click on the “Advanced…” button and check off “Run as administrator”.  That’s it.  Now when you log onto Windows your script will automatically start up, running as an administrator; allowing it to interact with any application and window like you had expected it to in the first place.

    ==< EDIT >==

    This method works for running AHK scripts that don’t require admin privileges at startup.  It only works for running AHK scripts as admin at Windows startup if you have disabled UAC in the registry in Windows 8, which you likely do not want to do (and I had done at the time of writing this article, but have since switched it back on).  For a better, UAC-friendly solution to running your AHK scripts as admin at startup, see my newer post to actually get your AHK script to run as admin at startup.

    If you do need your AHK script to run as admin and plan on manually double-clicking your AHK script to launch it though, then you can still use this trick of create a shortcut and setting it to Run As Admin in order to avoid having to right-click the AHK script and choose Run As Admin.

    ==</ EDIT >==

    image

    Happy coding!