如何获得活动会话用户SID?

时间:2016-09-06 13:55:13

标签: vbscript cmd

如何获取活动会话用户SID? (这是当前的用户会话)

我可以使用CMD命令执行此操作:

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

也许有人可以告诉我如何对VBScript做同样的事情?

“当前用户”是指“在UAC让我输入管理员凭据之前启动脚本的帐户”。

2 个答案:

答案 0 :(得分:0)

试试这个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
'******************************************************************

注意: 我是通过此链接获得的 How to find out logged on users SID with VBScript?

答案 1 :(得分:0)

获取当前登录域用户的SID

从命令行运行命令whoami /user以获取登录用户的SID

示例:

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

您可以使用批处理文件执行类似的操作:

@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