Get Currently Logged in username

2019-08-06 06:45发布

问题:

I am trying to get the logged in username of the user by using VBS.

I tried some codes which works when I run the script directly (Double Clicking it)

Set wshNetwork = CreateObject("WScript.Network")
strUser = wshNetwork.Username
WScript.Echo "Current User: " & strUser

However, what I need to do is to use CMD to run a scheduled task using the AT command. When it ran, the username would be the computer's name instead of the logged in user.

This problem also occurs when I run CMD as administrator and use wscript to run the script.

Is there any way to bypass this context and get the logged in user instead of the one that runs the script?

回答1:

The command

query session console

should provide what you need

For an easier to parse

quser console

EDITED - Included sample vbs code

Dim strCmd
    strCmd = "cmd /q /c ""quser console | find /i ""console"" "" "

Dim buffer 
    buffer = WScript.CreateObject("WScript.Shell").Exec(strCmd).StdOut.ReadAll()

Dim c, consoleUserName
    c = InStr(buffer,"console")
    If c > 2 Then
        consoleUserName = Trim(Mid(buffer,2,c-2))
    Else
        consoleUserName = ""
    End If

    WScript.Echo consoleUserName


回答2:

I suggest you execute the command

set

from the prompt. It may reveal a few items that are set in the environment that may be of interest.

set user

will censor the list so that only variables that start user will be displayed.



标签: vba vbscript cmd