Get the logged on user – code which works!

Some VBscript code which ACTUALLY works. I don’t understand some sites which share code. You go looking for VBscript code on the net to do something, and invariably IT DOES NOT WORK.

For one of two reasons:

  • it’s a code snippet, and you need to write code around it to get it to work
  • it’s a code snippet, which has been copied from somewhere else, where it did not work either.

The VBscript I’ll post in the CodeWhichWorks category will work because:

  • I use it in a production environment, so I know it works
  • I use it in a production environment, and I use this code as a memory jogger.

 

GetLoggedOnUser

Get the username, user domain & computer name of the user & computer which is running the VBscript.

Message box showing user and computer details '*********************************************************
' NAME: GetLoggedOnUser
'
' AUTHOR: Dale Robinson (WISEFAQ.COM)
' DATE  : September 2008
'
' COMMENT: Get the logged on user.
'
' Version: 1.0
'*********************************************************


Option Explicit
On Error GoTo 0

Dim bGotUserDetails
Dim sUserName, sUserDomain, sDisplay_ComputerName

Call fn_GetLoggedOnUser(sUserName,sUserDomain,sDisplay_ComputerName, bGotUserDetails)

If bGotUserDetails Then
MsgBox "Username: " + sUserName + VbCrLf + "Domain: " + sUserDomain + VbCrLf + "Computer Name: " + sDisplay_ComputerName,,"User details"
End If

WScript.Quit

Function fn_GetLoggedOnUser(fnsUserName,fnsUserDomain,fnsComputerName, boolresult)
' get some common computer / user details.
Dim objNet, objWSHShell, objEnv
On Error Resume Next
'get the username and domain
Set objNet = CreateObject("WScript.NetWork")

If Err.Number <> 0 Then
boolresult = False
Else
boolresult = True
End If

   fnsUserName = objNet.UserName
fnsUserDomain = objNet.UserDomain

'get the computer name
Set objWSHShell = WScript.CreateObject("WScript.Shell")

   If Err.Number <> 0 Then
boolresult = False
End If

   Set objEnv = objWSHShell.Environment("Process")

If Err.Number <> 0 Then
boolresult = False
End If

fnsComputerName = objEnv("COMPUTERNAME")
Set objNet = Nothing
Set objWSHShell = Nothing
Set objEnv = Nothing
On Error GoTo 0
End Function

You can download a zipped copy of GetLoggedOnUser.vbs here.

Bookmark and Share