How to get active session user SID?

2019-05-31 07:43发布

问题:

How to get active session user SID? (it is current user session)

I can do this using CMD command:

for /f "tokens=2-4" %a in ('qwinsta') do @if "%c"=="Active" wmic useraccount where name='%a' get sid

Maybe someone can tell me how to do same with VBScript?

By "current user" I mean "the account that started the script before UAC made me enter Admin credentials".

回答1:

Give a try for this vbscript :

Option Explicit
Dim strUser
strUser = CreateObject("WScript.Network").UserName
Wscript.echo "The SID of this username " & strUser & " is :" &_
vbcr & GetSIDFromUser(strUser)
'******************************************************************
Function GetSIDFromUser(UserName)
  Dim DomainName, Result, WMIUser
  If InStr(UserName, "\") > 0 Then
    DomainName = Mid(UserName, 1, InStr(UserName, "\") - 1)
    UserName = Mid(UserName, InStr(UserName, "\") + 1)
  Else
    DomainName = CreateObject("WScript.Network").UserDomain
  End If
  On Error Resume Next
  Set WMIUser = GetObject("winmgmts:{impersonationlevel=impersonate}!" _
    & "/root/cimv2:Win32_UserAccount.Domain='" & DomainName & "'" _
    & ",Name='" & UserName & "'")
  If Err.Number = 0 Then
    Result = WMIUser.SID
  Else
    Result = ""
  End If
  On Error GoTo 0
  GetSIDFromUser = Result
End Function
'******************************************************************

NB : I got it from this link How to find out logged on users SID with VBScript?



回答2:

Get SID for current logged in domain user

Run the command whoami /user from command line to get the SID for the logged in user.

Example:

c:\>whoami /user
USER INFORMATION
----------------
User Name      SID
============== ==============================================
mydomain\wincmd S-1-5-21-7375663-6890924511-1272660413-2944159
c:\>

And you can do something like that with a batch file :

@ECHO OFF
SETLOCAL enabledelayedexpansion
for /f "skip=1 tokens=1,2 delims=," %%a in ('Whoami /user /FO CSV') do ( 
    set "UserName=%%a"
    set "SID=%%b"
    echo The username logged is : !Username!
    echo.
    echo And its SID = !SID!
)
pause
exit


标签: vbscript cmd