I need to check whether the user executing the script has administrative privileges on the machine.
I have specified the user executing the script because the script
You can use script if you want to see if the logged on user is an administrator
Set objNetwork = CreateObject("Wscript.Network")
strComputer = objNetwork.ComputerName
strUser = objNetwork.UserName
isAdministrator = false
Set objGroup = GetObject("WinNT://" & strComputer & "/Administrators")
For Each objUser in objGroup.Members
If objUser.Name = strUser Then
isAdministrator = true
End If
Next
If isAdministrator Then
Wscript.Echo strUser & " is a local administrator."
Else
Wscript.Echo strUser & " is not a local administrator."
End If
I am not sure how to handle it when the script is run with "Runas" I am afraid.
This article has a nice chunk of code on how to enumerate the members of a group (copied here for convenience and edited to not use email address):
Function RetrieveUsers(domainName,grpName)
dim GrpObj
dim mbrlist
dim mbr
'-------------------------------------------------------------------------------
' *** Enumerate Group Members ***
'-------------------------------------------------------------------------------
' Build the ADSI query and retrieve the group object
Set GrpObj = GetObject("WinNT://" & domainName & "/" & grpName & ",group")
' Loop through the group membership and build a string containing the names
for each mbr in GrpObj.Members
mbrlist = mbrlist & vbTab & mbr.name & vbCrLf
Next
RetrieveUsers=mbrlist
End Function
You can then write a function to see if a user is in the list...
Function IsAdmin(user)
IsAdmin = InStr(RetrieveUsers("MachineName", "Administrators"), user) > 0
End Function
...and call it like this:
If IsAdmin("LocalAccount") Then
Wscript.Echo "LocalAccount is an admin"
Else
Wscript.Echo "LocalAccount is not an admin"
End If
User may be not in local administrator group. For example - domain admins. UAC usually blocks admin access to registry, shares e.t.c. even for administrators(onl y manual "run as admin" gets right)...
Here is my crazy way:
Set Shell = CreateObject("WScript.Shell")
set fso = CreateObject("Scripting.FileSystemObject")
strCheckFolder = Shell.ExpandEnvironmentStrings("%USERPROFILE%")
strCheckFolder = strCheckFolder+"\TempFolder"
if fso.FolderExists(strCheckFolder) then
fso.DeleteFolder(strCheckFolder)
end if
fso.CreateFolder(strCheckFolder)
tempstr = "cmd.exe /u /c chcp 65001 | whoami /all >" & strCheckFolder & "\rights.txt"
Shell.run tempstr
tempstr = strCheckFolder & "\rights.txt"
WScript.Sleep 200
Set txtFile = FSO.OpenTextFile(tempstr,1)
IsAdmin = False
Do While Not txtFile.AtEndOfStream
x=txtFile.Readline
If InStr(x, "S-1-5-32-544") Then
IsAdmin = True
End If
Loop
txtFile.Close
Function isAdmin
Dim shell
Set shell = CreateObject("WScript.Shell")
isAdmin = false
errorLevel = shell.Run("%comspec% /c net session >nul 2>&1", 0, True)
if errorLevel = 0
isAdmin = true
End If
End Function