Scripting Elevation on Vista


[Added 2007-07-02, 16:41 Eastern Time:  I was thoroughly and inexcusably remiss in failing to include a reference to Michael Murgolo’s excellent TechNet Magazine article, Script Elevation PowerToys for Windows Vista.  I’m rectifying that now.]


As I mentioned recently, although the RunAs.exe console utility still exists on Windows Vista and will let you run a program as another user, it will not run that program with elevated privileges. So if you use RunAs.exe to start a program with an administrator account, the program will run with that account’s profile and settings, but with standard user privileges only, not with the power to do computer administration. You can’t get an application to run with elevated privileges unless you go through the UAC elevation prompt. And RunAs.exe on Windows Vista (RTM, anyway) will not invoke that prompt.


What if you have batch files for XP or Server 2003 that called RunAs when administrative tasks needed to be performed? E.g., say there’s a line in your batch file to start CMD.EXE with elevated permissions that looks like this:


runas /u:Administrator “cmd.exe /t:fc /k cd /d c:\ && title *** Admin console *** ”


Is there another way to script the “run this program with elevated permissions” that RunAs gave you on XP/2003? Yes. First, create a small script file called “elevate.js” and put it in a folder in your PATH. (*) The contents of elevate.js should look like this:


// elevate.js — runs target command line elevated
if (WScript.Arguments.Length >= 1) {
Application = WScript.Arguments(0);
Arguments = “”;
for (Index = 1; Index < WScript.Arguments.Length; Index += 1) {
if (Index > 1) {
Arguments += ” “;
}
Arguments += WScript.Arguments(Index);
}
new ActiveXObject(“Shell.Application”).ShellExecute(Application, Arguments, “”, “runas”);
} else {
WScript.Echo(“Usage:”);
WScript.Echo(“elevate Application Arguments”);
}

Then replace “runas /u:Administrator” with “elevate”: (**)


elevate cmd.exe “/t:fc /k cd /d c:\ && title *** Admin console *** ”


Important note: the elevate.js script invokes the UAC prompt, but it will not let you bypass it. User interaction is still required.


With the default settings, the elevation prompt will prompt you for simple consent (click “continue”) if you are a member of the Administrators group, and prompt you for admin credentials if you are running as a standard user. If you are a member of the Administrators group, but would like to use a different account for the elevated task, you can change the computer’s security policy for the behavior of the elevation prompt for admins to “Prompt for credentials”. When the prompt appears, you can enter the credentials of a different administrative account.


Thanks to John Stephens of the Windows team for this script.


(*)  I highly recommend that scripts and other programs that may be used by elevated apps or are part of elevation sequences be kept in a folder that standard users cannot write to. I have a Utilities folder under %ProgramFiles% for this purpose.


(**)  Note that the quoting in this case needed to be rearranged a little as well: the first item passed to the script is the application to elevate; everything after that forms the rest of the command line for that application. If the quoting had been kept as-is, Windows would have tried to elevate an application called “cmd.exe /t:fc /k …”, which doesn’t exist. The quotes are still needed here so that the “&&” and everything after it remain on the command line to the elevated application. Otherwise the current command shell will parse it as part of the command it is running.

Comments (33)

  1. Chris Knight says:

    Um, OK.

    So why does my clean install of Vista Business allow me to do a RunAs /user:Administrator cmd.exe that then can delete/write files into the system folders?

    @Chris:  Interesting — I’ll have to check that out.  Did you 1) disable UAC, or 2) enable the built-in Administrator account, which is disabled by default?

    — Aaron

    [2007-07-02] @Chris:  I think I’ve identified the issue here.  By default, “Admin Approval Mode” is disabled for the built-in Administrator account, so any logons for that account run with full admin privileges.  So if you enable that account and then use RunAs.exe to start process using that account, it will run elevated and without a UAC elevation prompt.  Administrator is disabled by default; I think its primary purpose is for system recovery (e.g., in Safe Mode).  If you enable that account, you should also change the security option to enable Admin Approval Mode for that account.

    — Aaron

  2. sean e says:

    I do the same as Chris Knight (hey, ex-Beatnik?).

    I have not disabled UAC and I don’t think I did anything special to the admin account.  My account is a standard user but I leave an admin console open and can do anything in it without UAC prompts (aside from the initial one when first opening the console).  Running vista ultimate.

  3. sean e says:

    Did a little checking… I don’t have an account named Administrator, but do have one by another name – so I must have either created it or renamed and enabled the default one.

    Just noticed that I don’t explicitly use runas to open my prompt either.  I have a shortcut whose properties I modified to run as administrator (properties | shortcut | advanced – it must invoke a runas behind the scenes).

    @sean e:  You’re certainly getting an elevation prompt when you do that, right?  (Unless you’ve changed the security policy to elevate without prompting, which is very risky and strongly discouraged.)

    — Aaron

  4. Ramesh says:

    Here is another example(.vbs file)

    VBScripts and UAC elevation:

    http://www.winhelponline.com/articles/185/1/

  5. Mike Rickard says:

    working with Vista to run elevated is more “interesting” than with XP.

    “And RunAs.exe on Windows Vista (RTM, anyway) will not invoke that prompt.” – Well it will if the manifest of the program that you’re launching  shows that it needs to run as administrator.

    [Aaron Margosis]:  No it doesn’t.  Try runas /u:adminaccount dfrgui.exe.  I get
    RUNAS ERROR: Unable to run – dfrgui.exe
    740: The requested operation requires elevation.

    In an earlier post I outlined what we do to provide a system for our users to run things elevated, although they logon with ordinary user rights, and we don’t give them the local adminstrator password. http://blogs.msdn.com/aaron_margosis/archive/2005/03/11/394244.aspx#394978

    For vista we have to change a number of things. As this post outlines you have to use the runas verb with shellexecute to invoke the consent UI and get a process to run with a full token. This complicates matters as not everything has a runas verb. Because we’re working from the shell, we’re always looking at shell objects. Executables have a runas method, regular shortcuts to executables have a runas method, but “smart shortcuts” (the sort produced for self repairing applications by the MS installer) don’t. MMC documents seem to have a runas method.

    So our script will have to look for a runas method, and invoke it if there is one. If there isn’t, we’ll have to invoke the runas method on another shellexecute utility which launches whatever we want launched. This means that the consent UI refers not to what the user wants to launch, but to our utility, which is why we will invoke the runas verb on the shell object if we can, because then the consent UI will refer correctly. For that reason we’ll give MSIs and MSPs a runas method. The way the shell seems to work is to invoke the consent UI (and use the full token) simply because the runas method is what’s being invoked. So all you need to do is to copy the open method to a new runas method. (Incidentally, this is a sensible thing to have on an XP box, where you can then use an adminstrative account to install an MSI by simply selecting the runas methos you’ve created – you’ll be prompted for the credentials in the normal way.)

    We still in the process of trying to figure out how to deal with some other “features”. As Aaron pointed out recently, you can use this technique to elevate explorer, or at least you seem to be able to do so. However, we are going to have to do some more testing on what happens when you try to elevate explorer, and have other explorer windows already open. If you do this in regualr UAC mode, then it looks as though all your exisiting explorer windows are elevated.

    So it looks as though it should be possible to have a make me admin feature under vista at the cost of some more complicated scripting. For most users looking after their own computer this should be less necessary than it was for XP. As UAC for administrators will be the norm, and because of the way that integrity control works, the range of programs that work when installed via the consent UI by an administrative user with a split token, but don’t work when installed by a different administrative account should be much reduced. I’d still advocate using an account with no special privileges for operating a vista system. One of the bizarre consequences of UAC is that some programs which operate correctly, but with some limitations for unprivileged users will prompt for elevation when you don’t want this. e.g. regedit – Unless I actually want to edit the machine registry, which isn’t very often, I’d much rather open regedit with no special privileges to edit my own profile, and view the machine registry.

    [Aaron Margosis]:  Some apps are configured to run in the current context (asInvoker), some are configured to require elevation (requireAdministrator), and some — including regedit.exe and mmc.exe — are configured to require elevation if the user is an admin running with a filtered token (highestAvailable).  IMHO, the marking of regedit and mmc as highestAvailable is an unfortunate but understandable compromise for the Vista RTM timeframe.  Maybe a future blog post. 🙂

    Our last problem, how to deal with UAC style elevation prompts forced by hardware changes seems to be insoluble. Once the elevation prompt is on screen you can’t do anything except supply credentials or cancel. You can’t add yourself on the fly to the adminstrators group until after you’ve cancelled. So the best we’ll be able to do is to try to explain how to cancel, add on the fly, and then force the elevate prompt back again. This will require them to read the documentation we provide. Our experience is that most of our users regard documentation as an indication of a poor system: if they can’t get it to work without documentation then we should have designed it properly in the first place!

    [Aaron Margosis]:  Good luck.  The design goals of Windows Vista definitely assume that either the user is trusted with system administration privileges, or not.  We have found that most forms of “partial administrative capabilities” such as “Power Users” usually end up including an inexorable path to full administrative capabilities.  That’s why Power Users has been deprecated in Windows Vista, and why we didn’t include any kind of setuid or sudo functionality.

  6. sean e says:

    >@sean e:  You’re certainly getting an elevation >prompt when you do that, right?

    Yes, I get the prompt when I open the console.  After that initial one, I’m good for doing anything without further prompts.

    @sean e:  As expected.  If an elevated program starts another program, the new program will also run elevated.

    BTW, what you’re doing is not invoking RUNAS.EXE, the console utility program.

    — Aaron

  7. If you need to run command with full administrator permissions in Windows Vista, you could use the elevated

  8. rwx---rwx says:

    > Administrator is disabled by default […]

    > If you enable that account, you should also

    > change the security option to enable Admin

    > Approval Mode for that account.

    I think that’s a good idea.  But you have a better idea:

    [For other administrative accounts]

    > (Unless you’ve changed the security policy to

    > elevate without prompting, which is very risky

    > and strongly discouraged.)

    I think that’s a very good idea.  I think it should apply to the built-in Administrator account too, for exactly the same reason.  There should not be a default which changes the built-in Administrator account to elevate without prompting.  The default should put the same Admin Approval Mode on that account as it does on other administrative accounts, because any deviation is risky and strongly discouraged.

    [Aaron Margosis] The default is that admin-approval mode (AAM) is disabled for the built-in Administrator account, but that the built-in Administrator account itself is also disabled.  Its purpose (as I understand it) is to serve in emergencies such as system recovery, at which point you presumably wouldn’t want AAM to be in the way.  If you intend to use the built-in Administrator account for other purposes and enable the account, you should probably change its AAM setting at the same time.

    > We have found that most forms of “partial

    > administrative capabilities” such as “Power

    > Users” usually end up including an inexorable

    > path to full administrative capabilities.

    Yes.  Any administrator who wants to be administrator and intentionally sets out to be administrator should be allowed to be administrator.  But some of us peasants occasionally make typos or (more commonly for some of us) accidentally hit a mouse button while moving the mouse, causing unwanted operations to occur.  So some of us would be glad to be administrators only when we want to be, and be power users the rest of the time.  The prompts do help a bit, but I think that was no reason to get rid of power users.

    In old days, I used to set tape reels to r–r–r– except when intending to write to them.  I still sometimes set floppy disks to r-xr-xr-x except when intending to write to them.  I wish I could mount disk partitions as r-xr-xr-x.[*]  Sure, as a power user I have the power to change the settings at will, but at least I won’t usually do that accidentally, and at least it means I’d have to make at least two accidental mistakes in a row before doing serious damage.  Power users are useful.

    [Aaron Margosis] I’m not sure that we’re talking about the same thing.  I’m referring to Power Users, the “admin-lite” group that’s been present since NT 3.1.  It was intended as a middle ground, more powerful than Users, but less so than Administrators.  However, that ground proved to be untenable, as the access that was granted to Power Users allowed it to elevate to full system control.  That’s why it’s been deprecated.  For reference, see this KB article, Jesper’s blog post, and Mark Russinovich’s blog post

    [* Even in Linux I wish I could mount disk partitions as r-xr-xr-x.  Drivers disobey that setting when replaying journals, and I wish I could stop them.  But this is off-topic, sorry.]

  9. I made a PowerShell version of the JS script. See http://msgoodies.blogspot.com/2007/07/powershell-start-elevatedprocess.html

    [Aaron Margosis]  As I said here, Windows PowerShell is the coolest and most revolutionary technology we have shipped in a very long time.  Thanks for providing more evidence, Per! 🙂

  10. rwx---rwx says:

    “Administrator” account

    > Its purpose (as I understand it) is to serve

    > in emergencies such as system recovery, at

    > which point you presumably wouldn’t want AAM

    > to be in the way.

    OK, I see the point.

    “Power users” (admin-capable but not by default)

    > I’m not sure that we’re talking about the

    > same thing.  I’m referring to Power Users,

    We are.  We agree that power users have the capability to become admins.  You think there’s no purpose in letting admin-capable people run as power users until they deliberately decide to be admins.  I think there is a purpose, and I tried to explain why.  Vista’s prompts provide some of the same protections, because sometimes someone who fat-fingers a mouse key or keyboard key might get a second chance to avoid doing what they didn’t intend to so.  The power users group was a more powerful way to provide the same protections.  It’s like having the SETPRIV bit or knowing the root password, you deliberately enable privileges when you need them but you don’t enable them otherwise.  Oops sorry, s/you/I/.

    [Aaron Margosis]  Power Users (as it existed on XP and earlier) provides no such protections.  Running as Power User was tantamount to running as admin.  There were tons of things you could do to damage the system and/or other users.  More importantly, malware that runs in your session could immediately take over the entire system.  The whole idea of UAC is for end users (including people who administer their own systems) to have only the power they typically need for computer use — in which the system and other users cannot be touched.

  11. rwx---rwx says:

    > Running as Power User was tantamount to

    > running as admin.

    Already known and agreed.

    > More importantly, malware that runs in your

    > session could immediately take over the

    > entire system.

    OK, you mean that vulnerabilities in the capabilities of Power Users made it possible for malware to enable itself to do the same things without any further interaction with the user.  OK, that’s dangerous.

    I thought the idea behind power users (the ability to be admin when desired but not automatically being admin when not desired) was a good idea.  But now this reminds me of our other discussion:

    Now I notice that if Vista had a real MakeMeAdmin then there wouldn’t be much difference between standard users and power users.  The ability to temporarily add their own account to the administrators group would work for standard users as well as for power users.  So theoretically maybe there’s no need for power users, we just need MakeMeAdmin.

  12. Mike Rickard says:

    I said: "And RunAs.exe on Windows Vista (RTM, anyway) will not invoke that prompt." – Well it will if the manifest of the program that you’re launching  shows that it needs to run as administrator.

    [Aaron Margosis]:  No it doesn’t.  Try runas /u:adminaccount dfrgui.exe.  I get

    RUNAS ERROR: Unable to run – dfrgui.exe

    740: The requested operation requires elevation.

    Aaron is quite right, and I’m an idiot for not checking why I came to that conclusion. why I did is just interesting enough to report.

    What I had been doing was checking my privilege elevation utility. (This is a MakeMeAdmin kind of thing.) When I used this I saw the behaviour I claimed for runas: Only programs marked to require administrative rights were elevated. The reason is quite simple: After doing the necessary fiddling with group memberships the utility invokes runas like this:

    runas /u:adminaccount "shelexec dfrgui.exe"

    where shelexec is a simple command line program that invokes the shelexec function of the shell to launch something. We used this because it would launch non-executables such as MSIs and also shortcuts: the sort of things that you find via the GUI. We didn’t supply a verb to the function, so that it used the default verb. i.e. the verb that double-clicking would invoke. Hence the behaviour we saw was exactly the same as double-clicking on something: if it’s marked as requiring elevation and you have the right to do this, you get an elevation prompt, if it isn’t so marked it is simply launched without extra rights.

    The only effective difference from the script that Aaron uses is we used the default verb, his script uses the Runas verb.

  13. rws---rwx (idiot with an idiot system) says:

    > Running as Power User was tantamount to

    > running as admin.

    Already known and agreed, and now being revisited.

    Running as Power User was tantamount to running as Local System.  Running as Admin was tantamount to running as Local System.  Under Vista, running as Admin is *still* tantamount to running as Local System.

    Now please bear with me.  Sometimes I’m an Admin, therefore sometimes I’m an Idiot (already known and agreed).  Now I’ve just verified that even in Vista I can sometimes be Local System, and therefore Local System is sometimes an Idiot.  So please patiently explain this to me:

    Why didn’t Administrators disappear along with Power Users?  Why aren’t we running as Local System with UAC?

    [Aaron Margosis]  What would be the value of that?  Note that with Administrators you still have your own account, your own settings, preferences, etc.  LocalSystem was never designed to be used as an interactive logon.

    (Off-topic tangent:  why is cron setuid to Administrator instead of setuid to Local System?)

    [Aaron Margosis]  Is that how “cron” is default-configured in the Vista Subsystem for UNIX-based applications?

  14. Gayle says:

    2 UAC Settings have been documented as

    1. UAC:Behaviour of the elevation prompt for standard users

    Default: Prompt for credentials (home) / Automatically deny elevation requests (enterprise)

    2. User Account Control: Detect application installations and prompt for elevation

    Default: Enabled (home) / Disabled (enterprise)

    Where can I get details for the other editions?

    [Aaron Margosis] Gayle, what’s the source of your references?

    If I’m not mistaken, the default, out-of-the-box settings are the same for all Vista editions.  The security guidance for enterprise-managed systems is for same-desktop elevation to be blocked for standard users.  In this context, “home” and “enterprise” aren’t named editions as much as they are management contexts.

    HTH

  15. Gayle says:

    Besides seeing the default settings for both UAC Policies on the Explain tab of the policies’ Properties in Group Policy Editor, its also at this link :

    http://technet2.microsoft.com/WindowsVista/en/library/00d04415-2b2f-422c-b70e-b18ff918c2811033.mspx

    as follows –

    User Account Control: Behavior of the elevation prompt for standard users

    • Home: Prompt for credentials

    • Enterprise: No prompt

    & this link for both Policies, WHICH IS CORRECT?

    http://technet.microsoft.com/en-us/windowsvista/aa905117.aspx

    1. User Account Control: Behavior of the elevation prompt for standard users

      Home: Prompt for credentials

      Enterprise: No prompt

    2. User Account Control: Detect application installations and prompt for elevation

      Home: Enabled

      Enterprise: Disabled

    WRT your reply,

    How is Vista capable of detecting which  management contexts applies at any point in time to apply the defaults in case of home & enterprise?

    Please clarify what management contexts means & how the defaults get applied.

    [Aaron Margosis]  Gayle:  thanks for pointing those out.  That documentation is all incorrect.  The out-of-the-box defaults are the same for all editions of Windows Vista.  For “Behavior of the elevation prompt for standard users” it’s “Prompt for credentials”, and for “Detect application installations…” it’s “Enabled”.  Sorry for the confusion.  I’ve alerted the appropriate people to the errors.

  16. Gayle says:

    Is there a way to detect for a machine that has been upgraded from XP to Vista –  the exceptional case in which Admin Approval Mode for the Built-in Administrator is enabled by default.

    Is it possible to get the effective setting for this UAC policy – if it has not been explicitly configured ?

  17. Jonathan says:

    Gayle:  I chatted with Aaron about the question on this policy and he suggested that I reply to the post.  That policy is picked up dynamically, so you could technically just look at this reg value:

    HKLMSoftwareMicrosoftWindowsCurrentVersionPoliciesFilterAdministratorToken

    to see if it’s set to non-zero (i.e., turned on); if it’s 0 or missing, it’s turned off.

    That said, all the major caveats apply here that this is an implementation detail that’s certain to change or be removed in the future.

    In theory, you shouldn’t even need to check for it, since things will "just work" if your code is already running as a standard user and handling "over the shoulder" elevation (i.e., starting from a standard user account and elevating with a different user).

    –Jonathan

  18. Gayle says:

    In current Editions of Vista , are the UAC registry values present by default ? i.e. when it shows as Not Configured in the Group Policy Editor

  19. Jonathan says:

    With the exception of FilterAdministratorToken, I’d expect them all to be present by default.

  20. Peter Griessl says:

    “Drop elevation”?

    Is there any way to drop/reduce the elevation back to normal level inside an elevated script?

    1. elevate mysuperscript.bat

    2. mysuperscript.bat:

       …execute elevated commands

       drop elevation

       …execute standard commands

    Thanks for any hints!

    Peter Griessl, griessl@ihs.ac.at

    [Aaron Margosis] Not really.  It’s not safe to assume that the desktop user and the elevated context represent the same user.  Elevation may involve a different user’s credentials.  I haven’t tried this with script yet, but I would try to create a script that runs non-elevated, launches something elevated as needed (will be in a separate process), then performs the non-elevated operations.

  21. stefan kanthak says:

    Aaron:

    have you ever tested the script with pathnames and arguments containing blanks?

    Replace ‘= WScript.Arguments()’ with ‘= """ + WScript.Arguments() + """’ when this should work right!

  22. JOMYUT.NET says:

    When you are on Microsoft Windows Vista Platform. It is hard to create a script that use privilage command. One way is by use the command &quot;Runas&quot; as followC:&gt; Runas /user:Administrator cmdHowever, the above command will ask for Administrato

  23. nathan carnal says:

    My application sets a value in HKLMSoftwareMicrosoftWindowsCurrentVersionRun to add it to the startup.  In Vista, I receive access is denied.  What is the easiest way to correct this issue?  My application does not require admin priviledges except for this option (user can turn this feature on/off), but I do not want to prompt for elevation if it is not required.  Is this possible and if so what would you recommend to solve this?  Any help would be greatly appreciated.  Thanks ahead of time.

    [Aaron Margosis]  Does it need to be in HKLM?  If you put it in the equivalent key under HKCU, then it will launch every time that user logs on, and you won’t get access denied when you set or clear the value.

  24. nathan carnal says:

    Thanks for the quick response.  I would really like to make the changes to the HKLM b/c the application will run in a classroom setting and students will be logging on/off.  Any ideas?

    Thanks again.

    [Aaron Margosis]  Generally speaking, non-admin users shouldn’t be able to make configuration changes that affect other users.  Giving users the ability to change that key, in particular, is very dangerous.  I’d recommend just allowing individual users to change the settings for themselves, or just add it to HKLM as part of installation and don’t give the users the option to turn it off.

  25. Coolie says:

    I am elevating a windows installer setup.exe. The script runs fine on vista. On XP I either get ‘<full path>setup.ini’ not found or, in a directory with a shorter path I get "The windows installer service could not be accessed…."

  26. QuietTode says:

    In my environment, all the admins are set to ‘Prompt for Consent’. The leads to 740 errors with the RunAs command. To work around it, I created a shortcut to always run as admin and used the runas /netonly switch:

    C:WindowsSystem32runas.exe /netonly /user:domainusername "mmc c:windowssystem32dsa.msc"

    This works with the netonly switch, but not without.

  27. nwourms says:

    What is your opinion of this:

    http://technet.microsoft.com/en-us/magazine/cc162321.aspx

    [Aaron Margosis]  Yes, I referenced it in the italicized first line (added the day after I first posted).

  28. Colin says:

    I’m logged in as a local admin but I run MMC windows (AD users and computers, WSUS management etc) as a separate user.  This method is fine for non admin users but the only way I can find so far to run as a different user is to change User Account Control: Behavior of the elevation prompt for administrators in Admin Approval Mode to prompt for credentials which some what defeats the point of being a local admin.

    Thoughts?    

  29. erich says:

    i am using robocopy.exe (provided with the Microsoft Resource Kit Tools) to backup my system. on win xp i used runas to start a command line (cmd.exe) with a user in the "Backup Operators" group to (in turn) start robocopy.exe (as backup operator) to backup the system.

    is there any way to specify a particular user that is a non-admin (namely a backup operator) in the UAC prompt or with the elevate.js script mentioned in this post?

    in other words, how can i get this functionality with vista:

    runas /user:bo cmd.exe

    wehere the user "bo" is merely within the "Backup Operators" not the "Administrators" group? is there a way to add the "bo" user to the UAC prompt or to specify when using the elevate.js script?

  30. quux says:

    I’m writing a vbscript which will ultimately run on many versions of Windows – XP, 2003, Vista, 2008 – maybe even 2000. Within the script are a few things that will require elevated access – but they are conditional events.

    What I need is a way to *detect* whether the script is currently in an elevated context or not, so that the script can intelligently decide whether to attempt elevated actions.

    After much experimentation and searching, I have yet to find a solid method of doing this, that doesn’t require 3rdparty utilities which may or may not be present.

    Any thoughts, Aaron?

    [Aaron Margosis]  If the question is “am I running with full admin rights”, then how about just trying to do something benign that requires full admin rights?  How about this:

    option explicit

    Function IsAdmin()
        dim fso, sFilename
        Randomize
        set fso = WScript.CreateObject(“Scripting.FileSystemObject”)
        on error resume next
        sFileName = “C:temporary-test-file-” & Rnd()
        fso.CreateTextFile sFileName
        if err.number = 0 then
            fso.DeleteFile sFileName
            IsAdmin = True
        else
            IsAdmin = False
        end if
    End Function

    If IsAdmin Then
     WScript.Echo “Running as admin”
    Else
     WScript.Echo “Not running as admin”
    End if

    This should work on all the Windows versions you mentioned except Windows 2000 — non-admins are allowed to create files in C: on Windows 2000, but not on any version of Windows since.

    HTH

  31. Darwin says:

    Aaron,

    I have put together a couple scripts (VBS and CMD) that use a passive method to detect admin rights (rather than writing stuff to test rights) and works on XP through Windows 7.  It is based on whether the user can get a directory of the system profile folder.  Would love to hear if you can think of scenarios where it would not work:

    Function CSI_IsAdmin()

     ‘For information and updates see http://CSI-Windows.com/toolkit/CSI_IsAdmin

     ‘For more comprehensive script see http://CSI-Windows.com/toolkit/ifuserperms

     Dim oShell : Set oShell = createobject("wscript.shell")

     Dim oExec : Set oExec = oShell.Exec("%comspec% /c dir """ & oShell.RegRead("HKLMSOFTWAREMicrosoftWindows NTCurrentVersionProfileListS-1-5-18ProfileImagePath") & """  2>&1 | findstr /I /C:""Not Found""")

     Do While oExec.Status = 0

       WScript.Sleep 100

     Loop

     If oExec.ExitCode <> 0 Then CSI_IsAdmin = True

    End Function

    It is downloadable here: http://csi-windows.com/toolkit/csi-isadmin

    The above script does not do any advanced detections like whether a user *Could* elevate.  

    So I have also put together a very comprehensive vbscript to snoop token information and determine admin rights on XP through Windows 7.  Also reports whether UAC is turned on or off and whether it is set to silent.

    It is here: http://csi-windows.com/toolkit/csi-issessionvbs

  32. Bill Stewart says:

    My ‘Elevation Toolkit’ is like elevate.js except that it uses the ShellExecuteEx and thus has some features some might find useful, such as waiting for the elevated program to complete and configuring its window state. You can get it from here: http://www.westmesatech.com/misctools.html

Skip to main content