Search code examples
javascriptwindowsjscriptwshwindows-scripting

Detect if JScript is running elevated?


I have a JScript that is designed to run on a Windows platform in a .js file (not a web browser script.) Can I detect if my script is running elevated, or with administrative privileges?


Solution

  • OK. I think I got it. Thanks to this poster, this seems to work:

    function isRunningElevated()
    {
        //Checks if this scrpt is running elevated
        //RETURN:
        //      = 'true' if yes
        var res = runCommandNoWindow("net session");
        return res === 0;
    }
    
    function runCommandNoWindow(strCmd)
    {
        //Run command
        //RETURN:
        //      = Integer returned by the command
        var res = null;
    
        try
        {
            var oShell = WScript.CreateObject("WScript.Shell");
            res = oShell.Run(strCmd, 0, true);  //No window, wait to finish!
        }
        catch(e)
        {
            //Failed
            res = null;
        }
    
        return res;
    }