?
Solved

VB Script to get logon user name

Posted on 2008-11-17
14
Medium Priority
?
4,046 Views
Last Modified: 2012-05-05
I am trying to build a VB script that will set three variables to the logged on user name, computer, date / time on a XP desktop and then write those variables out to log file.
0
Comment
Question by:bosn1
  • 7
  • 3
  • 2
  • +1
14 Comments
 
LVL 35

Expert Comment

by:Joseph Daly
ID: 22975501
Does it have to be a VBscript? How bout a windows batch


echo %clientname% >>c:\out.txt
date /t >> c:\out.txt
time /t >>c:\out.txt
 
 

Open in new window

0
 
LVL 35

Expert Comment

by:Joseph Daly
ID: 22975505
Sorry ignore that first post.
echo %username% >>c:\out.txt
date /t >> c:\out.txt
time /t >>c:\out.txt

Open in new window

0
 
LVL 7

Expert Comment

by:Hubasan
ID: 22975581
Hi bosn1,

All you need to get a logon user name and computer name is this:

Set oNet = CreateObject("WScript.Network")
sCurrentUser = oNet.UserName
sComputer = oNet.ComputerName
WScript.Echo "Current User:" & vbTab & sCurrentUser &_
vbCrLf & "Computer Name: " & vbtab & sComputer

as for the rest of it, I'm not sure what exactly do you need. Can you please clarify what exactly are you trying to do?
Are you just trying to create a script to get Username, Computername and date to a log file? If so here is the script below:

Set oNet = CreateObject("WScript.Network")
Set oFS = CreateObject("Scripting.FileSystemObject")
 
sCurrentUser = oNet.UserName
sDomain = oNet.UserDomain
sComputer = oNet.ComputerName
 
sScriptName = WScript.ScriptName
sScriptPath = WScript.ScriptFullName
sLog = Replace(sScriptName, ".vbs", ".log")
sLogFile = Replace(sScriptPath, sScriptName, sLog)
 
Set oLogFile = oFS.CreateTextFile(sLogFile, True)
 
oLogFile.WriteLine "Current Date: " & "," & CurrentDateTime
oLogFile.WriteLine "Current User: " & "," & sCurrentUser
oLogFile.WriteLine "Computer Name: " & "," & sComputer
 
Function CurrentDateTime()
	CurrentDateTime = FormatDateTime(now, vbLongDate) & " @ " & FormatDateTime(now, vbLongTime)
End Function

Open in new window

0
Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

 
LVL 7

Expert Comment

by:Hubasan
ID: 22975586
Oh sorry, didn't realize someone was already helping you...
0
 

Author Comment

by:bosn1
ID: 22975739
Hubasan

I have to shutdown our desktop computers each night at a specific time.  I have a script that displays a message giving the user a 30 minute warning along with the option to cancel the process.

I have to log the user name, computer name and the date/time for each computer that is shutdown.

I am using the AT command with the interactive switch to schedule the task so that the warning is visible to any logged on user.
0
 
LVL 18

Expert Comment

by:exx1976
ID: 22975853
No, he wasn't getting any help, hubasan..   He asked for VBS and got batch xxd..  You were on the right track.
0
 
LVL 7

Expert Comment

by:Hubasan
ID: 22976109
Thanks for your comment exx1976. I don't like to impose when other experts are trying to help, and this happens often where I would look at the post and there would be no reply, so I write a script and post it and after that refresh I find out somebody else already posted minutes before me.

Hi bosn1,

So you already have the script that initiates the shutdown and notifies the user. Can you integrate my script above to yours so that it logs all that information? My script will create a log file in the same folder where you start the script from.
Let me know if you need any further assistance.
0
 
LVL 18

Expert Comment

by:exx1976
ID: 22976330
I know what you mean man.  Happens to me often where I'll spend 15-20 minutes whipping up something for someone and then I post it, only to find that someone beat me to it by a minute or two.  LOL
0
 

Author Comment

by:bosn1
ID: 22988358
Hubasan,

I hope to try integrating your script tomorrow morning.  I will let you know how it goes.

Regards
0
 
LVL 7

Expert Comment

by:Hubasan
ID: 22988393
No problem. Let me know if I can help further.
0
 

Author Comment

by:bosn1
ID: 22993759
I think I may be trying mix oil and water.  I copied your script into what I have already but it doesn't complie.  I am using Visual Basic 2005 Express.  I am new to this and Express seemed to be a bit easier to use.  This is he code that I have so far;

Public Class Form1
   
    Function CurrentDateTime()
        CurrentDateTime = FormatDateTime(now, vbLongDate) & " @ " & FormatDateTime(now, vbLongTime)
    End Function

    Private targetDT As DateTime
    Private WithEvents tmr As New Timer

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        targetDT = DateTime.Now.AddMinutes(30)
        tmr.Interval = 1000
        tmr.Start()

    End Sub

    Private Sub tmr_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmr.Tick
        Dim ts As TimeSpan = targetDT.Subtract(DateTime.Now)
        Dim shutdown
        Dim wscript
        shutdown = "shutdown.exe -s -f"
        wscript = CreateObject("WScript.shell")
        If ts.TotalMilliseconds <= 0 Then
            tmr.Stop()
            wscript.run("shutdown")
            'MessageBox.Show("Time's up!")
        Else
            lblTimer.Text = ts.Minutes & ":" & ts.Seconds.ToString.PadLeft(2, "0")
        End If
    End Sub

    Private Sub lblWarning_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblWarning.Click

    End Sub

    Private Sub lblBanner_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lblBanner.Click

    End Sub

    Private Sub btnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCancel.Click
        Me.Close()
    End Sub
End Class
0
 
LVL 7

Accepted Solution

by:
Hubasan earned 1000 total points
ID: 22994241
Hi Bosn1,

VB Scripts will not compile in Visual Basic, since VBS is designed to be compiled on execution by Windows Scripting Host client on every Windows OS. Structure of VBS files is very similar to Code from VB but it's different enough to cause problems.
I will include your part of the code in my script and all you would have to do is copy the code into a plain text file and save it as "filename.vbs", where filename is what ever you want. Then use an AT command to schedule execution of VBS file. However, you need to know that if you are executing a VBS file through command line like what you will be doing, then you have to execute it with wscript.exe or cscript.exe. Then pretty much have the same options (http://msdn.microsoft.com/en-us/library/0fs17b0s(VS.85).aspx) , the only difference is that cscript is executing in the command console and it will not show any prompts/msgboxes  to the user, and wscirpt will and will not launch in the console, but rather in the pure windows environment.


Here is an example of a command line execution of a VB Script:

"C:\Windows\System32\wscript.exe C:\myscript.vbs"

This command would tell wscript.exe client to execute C:\myscript.vbs

Give me couple of hours and I'll have your script.
0
 
LVL 7

Expert Comment

by:Hubasan
ID: 23095381
Hi Bosn1,

Sorry I didn't respond earlier, I was out of the country for holidays. I just came back and I remembered that I still owe you a script. If you still need it you can find the code below. Thank you for the points, and here is your script.

You should set it up the same way you did your original script. Use AT command and execute it. What it will do is present the user with a message that computer is shutting down in 30 minutes and ask them to save all of their work and only available option is an OK button. This message will be on the screen for 30 seconds and disappear by itself or user can click OK to make it go away immediately . Then after 4.5 minutes it will appear again. Saying that they now have 25 minutes to save all of their work...etc...
When the time expires they will be presented with a final message that gives them the option to cancel the Shutdown. If they do not or if they don't press anything on that final message it will force close all the software and execute the shutdown of the PC.
If there is anything you want to change, please feel free to ask, I owe you that much, even tho the issue is closed.
Set oNet = CreateObject("WScript.Network")
Set oFS = CreateObject("Scripting.FileSystemObject")
Set oWS = CreateObject("Wscript.Shell")
 
Const cTitle = "Computer Shutting Down!"
sCurrentUser = oNet.UserName
sDomain = oNet.UserDomain
sComputer = oNet.ComputerName
 
sScriptName = WScript.ScriptName
sScriptPath = WScript.ScriptFullName
sLog = Replace(sScriptName, ".vbs", ".log")
sLogFile = Replace(sScriptPath, sScriptName, sLog)
 
Set oLogFile = oFS.CreateTextFile(sLogFile, True)
 
i = 0
sMin = 30
Do Until i = 6
	sMessage = oWS.Popup("Your computer will be shutting down in " & sMin & " minutes." & vbCrLf &_ 
	"Please save all of your work as soon as you can." & vbCrLf & vbCrLf &_
	"This message will repeat every 5 minutes.",30 ,cTitle, vbExclamation)
	WScript.Sleep(270000)
	i = i + 1
	sMin = sMin - 5
Loop
 
sMessage1 = oWS.Popup("Your Computer is being Shut down momentarily!" & vbCrLf &_
"If you want to proceed please press YES to continue!",30 ,cTitle, vbYesNo+vbExclamation)
If sMessage1 = vbYes Or sMessage1 =-1 Then	
	oLogFile.WriteLine "Current Date: " & "," & CurrentDateTime
	oLogFile.WriteLine "Current User: " & "," & sDomain & "\" & sCurrentUser
	oLogFile.WriteLine "Computer Name: " & "," & sComputer
	oWS.Run "shutdown -s -f",2 ,False
Else
	oWS.Popup "Computer Shutdown aborted, exiting script!", 10, cTitle, vbInformation
	WScript.Quit
End If 
 
Function CurrentDateTime()
	CurrentDateTime = FormatDateTime(now, vbLongDate) & " @ " & FormatDateTime(now, vbLongTime)
End Function

Open in new window

0
 
LVL 7

Expert Comment

by:Hubasan
ID: 23095397
Oh yeah and the script will create the log file with current date-time, UserName, and Computer Name in the same folder where it's executed from, but you can change that by changing the "sLogFile" variable to any path you want.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

How to deal with a specific error when using the Enable-RemoteMailbox cmdlet to create a mailbox in the cloud-based service, for an existing user in an on-premises Active Directory.
Most folks would know the basics of how Dropbox works, so that’s not the purpose of this article. Security is what it’s all about, so here I’ll share how I choose to secure my Dropbox Account and the Data it contains.
Windows 8 came with a dramatically different user interface known as Metro. Notably missing from that interface was a Start button and Start Menu. Microsoft responded to negative user feedback of the Metro interface, bringing back the Start button a…
The Task Scheduler is a powerful tool that is built into Windows. It allows you to schedule tasks (actions) on a recurring basis, such as hourly, daily, weekly, monthly, at log on, at startup, on idle, etc. This video Micro Tutorial is a brief intro…

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question