How to Make a VBScript Timer - vbscript

I need to have a timer appear in a message box, coded in vbs. The message box needs to be in the bottom left corner of the screen, just above the start menu. It needs to not be able to exit, meaning it cannot be listed on the task bar (hopefully) and have no minimise/exit buttons. It needs to stay on top of all the other windows. It also needs to start at 20 minutes, counting down in seconds. I hope someone can help me with this - it's for a computer lab.
Thanks,
Matthew

Try something like that :
Option Explicit
Dim Title,ws,nMinutes,nSeconds,sMessage
Title = "Counting Down to Shutdown"
Set ws = CreateObject("wscript.Shell")
nMinutes = 20
nSeconds = 0
sMessage = "<font color=Red size=2><b>Counting Down to Shutdown"
'Open a chromeless window with message
with HTABox("lightBlue",100,250,0,630)
.document.title = "Counting Down Notification to Shutdown"
.msg.innerHTML = sMessage
do until .done.value or (nMinutes + nSeconds < 1)
.msg.innerHTML = sMessage & "<br>" & nMinutes & ":" & Right("0"&nSeconds, 2) _
& " remaining</b></font><br>"
wsh.sleep 1000 ' milliseconds
nSeconds = nSeconds - 1
if nSeconds < 0 then
if nMinutes > 0 then
nMinutes = nMinutes - 1
nSeconds = 59
end if
end if
loop
.done.value = true
.close
end with
ws.Popup "TIME IS OVER !","5",Title,0+48 'Afficher un Popup durant 5 secondes puis on quitte le script
'Command="cmd /c Shutdown.exe -s -t 30 -c " & DblQuote("Sauvegarder votre Travail car l'ordinateur va rebooter dans 30 secondes")
'Executer = WS.Run(Command,0,False)
'*****************************************************************
Function HTABox(sBgColor, h, w, l, t)
Dim IE, HTA, sCmd, nRnd
randomize : nRnd = Int(1000000 * rnd)
sCmd = "mshta.exe ""javascript:{new " _
& "ActiveXObject(""InternetExplorer.Application"")" _
& ".PutProperty('" & nRnd & "',window);" _
& "window.resizeTo(" & w & "," & h & ");" _
& "window.moveTo(" & l & "," & t & ")}"""
with CreateObject("WScript.Shell")
.Run sCmd, 1, False
do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop
end with 'WSHShell
For Each IE In CreateObject("Shell.Application").windows
If IsObject(IE.GetProperty(nRnd)) Then
set HTABox = IE.GetProperty(nRnd)
IE.Quit
HTABox.document.title = "HTABox"
HTABox.document.write _
"<HTA:Application contextMenu=no border=thin " _
& "minimizebutton=no maximizebutton=no sysmenu=no SHOWINTASKBAR=no >" _
& "<body scroll=no style='background-color:" _
& sBgColor & ";font:normal 10pt Arial;" _
& "border-Style:inset;border-Width:3px'" _
& "onbeforeunload='vbscript:if not done.value then " _
& "window.event.cancelBubble=true:" _
& "window.event.returnValue=false:" _
& "done.value=true:end if'>" _
& "<input type=hidden id=done value=false>" _
& "<center><span id=msg> </span><br>" _
& "<input type=button id=btn1 value=' OK ' "_
& "onclick=done.value=true><center></body>"
HTABox.btn1.focus
Exit Function
End If
Next
MsgBox "HTA window not found."
wsh.quit
End Function
'*****************************************************************

Related

VBScript Error - Object Required ObjTSO

'========================================================================
'## Global Object and Variable Settings
'========================================================================
Dim WshShell: Set WshShell = CreateObject("WScript.Shell")
Dim objFSO: Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim strSystemDrive: strSystemDrive = WshShell.ExpandEnvironmentStrings("%SystemDrive%")
'========================================================================
'## Main Code
'========================================================================
'On Error Resume Next
'---------------------------------------------------------------------------------------------------------------------------
'## Script Variables
'---------------------------------------------------------------------------------------------------------------------------
Dim strFolder: strFolder = strSystemDrive & "\Endpoint Reboot Info"
Dim strFile: strFile = strSystemDrive & "\Endpoint Reboot Info\Endpoint_Reboot_Logfile.txt"
strcurrentDateTime = Now()
Dim string0: string0 = "Endpoint restart analysis initialized"
Dim string1: string1 = "Calculating the endpoint uptime .. If greater than 14 days, machine will be restarted"
Dim string2: string2 = "Warning: The current OS Uptime exceeds 14 days! This system will be rebooted!"
Dim string3: string3 = " As the current OS Uptime is less than 14 days, this system will NOT be rebooted currently"
Dim string4: string4 = "This system will restart now!"
Dim string5: string5 = "User has clicked cancel, hence PC was NOT restarted"
Dim string6: string6 = "User has clicked OK. Restarting PC now.."
'---------------------------------------------------------------------------------------------------------------------------
'## Code for creating the folder and file necessary for logging and initializing the log file
'---------------------------------------------------------------------------------------------------------------------------
Function CreateLogFile(filename)
Dim f: set f = objFSO.OpenTextFile(strFile, 8, True)
f.WriteLine strcurrentDateTime & " " & string0
f.WriteLine strcurrentDateTime & " " & string1
Set CreateLogFile = f
End Function
'---------------------------------------------------------------------------------------------------------------------------
'## Code for checking endpoint OS uptime and force restarting post message display to end user
'---------------------------------------------------------------------------------------------------------------------------
Dim objTSO: Set objTSO = CreateLogFile(strFile)
strComputer = "."
Const FOR_APPENDING = 8
SET objWMIDateTime = CREATEOBJECT("WbemScripting.SWbemDateTime")
SET objWMI = GETOBJECT("winmgmts:\\" & strComputer & "\root\cimv2")
SET colOS = objWMI.InstancesOf("Win32_OperatingSystem")
FOR EACH objOS in colOS
objWMIDateTime.Value = objOS.LastBootUpTime
objTSO.WriteLine "Last Boot Up Time: " & objWMIDateTime.GetVarDate & vbcrlf & _
"System Up Time: " & TimeSpan(objWMIDateTime.GetVarDate,NOW) & _
" (hh:mm:ss)"
NEXT
FUNCTION TimeSpan(dt1, dt2)
' Function to display the difference between
' 2 dates in hh:mm:ss format
IF (ISDATE(dt1) AND ISDATE(dt2)) = FALSE THEN
TimeSpan = "00:00:00"
EXIT FUNCTION
END IF
seconds = ABS(DATEDIFF("S", dt1, dt2))
minutes = seconds \ 60
hours = minutes \ 60
minutes = minutes MOD 60
seconds = seconds MOD 60
IF LEN(hours) = 1 THEN hours = "0" & hours
TimeSpan = hours & ":" & _
RIGHT("00" & minutes, 2) & ":" & _
RIGHT("00" & seconds, 2)
If (hours > 336) Then
f.WriteLine strcurrentDateTime & " " & string2
Dim retval: retval = InputBox("Warning!: The current OS Uptime exceeds 14 days! This system will be rebooted! Please save ALL of your work and ONLY then click OK")
If IsEmpty(retval) Then
msgbox ("User has terminated the action by clicking cancel")
objTSO.WriteLine string5
Else
objTSO.WriteLine string6
WshShell.Run "shutdown.exe -R -T 0"
End If
Else
WScript.Sleep 10000
strcurrentDateTime = Now()
objTSO.WriteLine strcurrentDateTime & string3
WScript.Quit
End If
f.Close()
END FUNCTION
'---------------------------------------------------------------------------------------------------------------------------
'## End of code/VB Script
'---------------------------------------------------------------------------------------------------------------------------
I have now put up the full script as suggested. Please help with below queries:
This Line is not getting written into the log file
objTSO.WriteLine "Last Boot Up Time: " & objWMIDateTime.GetVarDate & vbcrlf & _
"System Up Time: " & TimeSpan(objWMIDateTime.GetVarDate,NOW) & _
" (hh:mm:ss)"
Also please check the logic of the code by changing the (hours>336) condition. This script will be executed locally on the machines, so instead of the previous reboot function, i have now modified it to WshShell.Run "shutdown.exe -R -T 0"
Please guide! Thanks!!
Your function CreateLogFile creates/opens the file, but then closes it right away:
Function CreateLogFile()
If objFSO.FileExists(strFile) Then
Set objTSO = objFSO.OpenTextFile(strFile, FOR_APPENDING)
objTSO.WriteLine strcurrentDateTime & " " & string0
objTSO.WriteLine strcurrentDateTime & " " & string1
objTSO.Close()
Else
objFSO.CreateTextFile(strFile)
Set objTSO = objFSO.OpenTextFile(strFile, FOR_APPENDING)
objTSO.WriteLine strcurrentDateTime & " " & string0
objTSO.WriteLine strcurrentDateTime & " " & string1
objTSO.Close()
End If
End Function
meaning that when the function returns the file handle is already closed, causing all subsequent attempts to write to the file (without opening it again) to fail.
What you actually want to do is change your function to something like this:
Function CreateLogFile(filename)
Dim f : Set f = objFSO.OpenTextFile(filename, 8, True)
f.WriteLine Now & " " & string0
f.WriteLine Now & " " & string1
Set CreateLogFile = f
End Function
Dim objTSO : Set objTSO = CreateLogFile(strFile)
...
objTSO.Close 'at the end of the script
Setting the 3rd parameter of the OpenTextFile method to True causes it to create the file in case it's missing.

Checking Installed programs

I need help in finding installed software version, license etc.
the below script works fine but it lists out all the installed softwares.
But am trying to find out a particular software.It gives nice output, can you help me here.
==================================================
'This script outputs to a .tsv file a list of applications installed on the computer
'Output file is software.tsv
'Usage: cscript applications.vbs
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.CreateTextFile("C:\WINDOWS\system32\temp\software.tsv", True)
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
("Select * from Win32_Product")
objTextFile.WriteLine "Caption" & vbtab & _
"Description" & vbtab & "Identifying Number" & vbtab & _
"Install Date" & vbtab & "Install Location" & vbtab & _
"Install State" & vbtab & "Name" & vbtab & _
"Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
& "Version"
For Each objSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Description & vbtab & _
objSoftware.IdentifyingNumber & vbtab & _
objSoftware.InstallDate2 & vbtab & _
objSoftware.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _
objSoftware.Version
Next
objTextFile.Close
======================================================
i just looking for details of C:\Program Files\HP\hponcfg\hponcfg.exe and i do not bother about other installed softwares, by default the above script gives the details of all the softwares, but i just do not need that.
where do i insert this line in the script.??
regards,
Dharanesh,
Check this modification, i tried it with name Google, so check it if retruns for you what do you expect or not ?
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Ws = CreateObject("WScript.Shell")
LogFile = "software.tsv"
if objFSO.FileExists(LogFile) Then
objFSO.DeleteFile(LogFile)
End if
Set objTextFile = objFSO.OpenTextFile(LogFile,8,True)
MySoftware = "Google"
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colSoftware = objWMIService.ExecQuery _
("Select * from Win32_Product where Name Like " & CommandLineLike(MySoftware))
objTextFile.WriteLine "Caption" & vbtab & _
"Description" & vbtab & "Identifying Number" & vbtab & _
"Install Date" & vbtab & "Install Location" & vbtab & _
"Install State" & vbtab & "Name" & vbtab & _
"Package Cache" & vbtab & "SKU Number" & vbtab & "Vendor" & vbtab _
& "Version"
For Each objSoftware in colSoftware
objTextFile.WriteLine objSoftware.Caption & vbtab & _
objSoftware.Description & vbtab & _
objSoftware.IdentifyingNumber & vbtab & _
objSoftware.InstallDate2 & vbtab & _
objSoftware.InstallLocation & vbtab & _
objSoftware.InstallState & vbtab & _
objSoftware.Name & vbtab & _
objSoftware.PackageCache & vbtab & _
objSoftware.SKUNumber & vbtab & _
objSoftware.Vendor & vbtab & _
objSoftware.Version
Next
objTextFile.Close
ws.run "Notepad software.tsv"
'**************************************************************************
Function CommandLineLike(MySoftware)
MySoftware = Replace(MySoftware, "\", "\\")
CommandLineLike = "'%" & MySoftware & "%'"
End Function
'**************************************************************************
How to get the extended information of a file ?
For example this vbscript can get the extended information of Firefox.exe :
Option Explicit
Dim fso,ws,RootFolder,LogFile,stFolder,stFile,oShell,oFolder,oFile,i
Set fso = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("WScript.Shell")
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "txt"
If fso.FileExists(LogFile) Then
fso.DeleteFile(LogFile)
End If
stFolder = Ws.ExpandEnvironmentStrings("%PROGRAMFILES%\Mozilla Firefox")
stFile ="firefox.exe"
Set oShell = CreateObject("Shell.Application")
Set oFolder = oShell.Namespace(stFolder)
Set oFile = oFolder.Items.Item(stFile)
'Displays extended file properties
For i = 0 to 34
WriteLog("[" & i & "] " & oFolder.GetDetailsOf(oFolder.Items, i ) & " : " & oFolder.GetDetailsOf(oFile, i))
Next
ws.run DblQuote(LogFile)
'*********************************************************************************************************************
Sub WriteLog(strText)
Dim fs,ts,LogFile
Const ForAppending = 8
LogFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "txt"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(LogFile,ForAppending,True)
ts.WriteLine strText
ts.Close
End Sub
'*********************************************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************************************
Or if you want to check the version of Firefox installed and if it is uptodate or not try this vbscript :
Option Explicit
Const ForWriting = 2
Const HKEY_CLASSES_ROOT = &H80000000
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const HKEY_USERS = &H80000003
Const REG_SZ = 1
Const REG_EXPAND_SZ = 2
Const REG_BINARY = 3
Const REG_DWORD = 4
Const REG_MULTI_SZ = 7
Dim RC , sPath, sNames, iTypes, sValue, objRegistry
Dim ROOT, i, j , msg, sKey, RC1, sKeyNames, fso, Fich
Set fso = CreateObject("Scripting.FileSystemObject")
Set Fich = fso.OpenTextFile("Version.txt", ForWriting, true)
Dim shell : Set shell = CreateObject("WScript.Shell")
sPath = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
ROOT = HKEY_LOCAL_MACHINE
Dim OK
OK = False
Set objRegistry = GetObject("WinMgmts:root\default:StdRegProv")
RC1 = objRegistry.EnumKey(ROOT, sPath, sKeyNames)
If (RC1 = 0) And (Err.Number = 0) And Not IsEmpty(sKeyNames) Then
For j = LBound(sKeyNames) To UBound(sKeyNames)
RC = objRegistry.EnumValues(ROOT, sPath & sKeyNames(j), sNames, iTypes)
If (RC = 0) And (Err.Number = 0) And IsArray(sNames) Then
If VerifTypes(ROOT, sPath & sKeyNames(j), iTypes) And OK Then Fich.WriteLine vbNewLine & sKeyNames(j) & " : "
For i = LBound(iTypes) To UBound(iTypes)
If iTypes(i) = REG_SZ Then
RC = objRegistry.GetStringValue(ROOT , sPath & sKeyNames(J), sNames(i), sValue)
If (LCase(sNames(i)) = "displayname" And sValue <> "") Or (LCase(sNames(i)) = "displayversion" And sValue <> "") Then
If InStr(1,LCase(sValue),"firefox") > 0 Then
msg = msg & sNames(i) & " = " & sValue
OK = True
MsgBox sValue & VbcrLf & "La version installée du soft Firefox est : "& ExtractVersion(sValue),64,"La Version installée du Soft Firefox"
Dim MyVer,NetVersion,URL,ws
MyVer = ExtractVersion(sValue)
URL = "http://www.mozilla.org/fr/firefox/new/"
NetVersion = GetFirefoxMajorVersion(URL)
msgbox NetVersion
If CompareVersions(MyVer,NetVersion) = -1 Then
MsgBox "La dernière version de Firefox est : " & NetVersion & VbCrlf &_
"Il y a une mise à jour en ligne !",48,"Il y a une mise à jour en ligne ! "
set ws = CreateObject("WScript.Shell")
ws.run URL
Else
MsgBox "Firefox est à jour !",64,"Firefox est à jour !"
end if
Fich.Write msg & vbNewLine & "La version installée du soft Firefox est : "& ExtractVersion(sValue) & vbNewLine
End If
End If
OK = False
End If
msg = ""
Next ' pour i
'MsgBox msg
Else
'Msgbox "L'erreur suivante est survenue : " & Err.Description
End If
Next ' pour J
Fich.Close
End If
Shell.run "version.txt"
'******************************************************************************************************************
Function Lsh(ByVal N, ByVal Bits)
Lsh = N * (2 ^ Bits)
End Function
'***************************************************************************************
Function VerifTypes(ROOT, strPath, Types)
' Cette fonction vérifie si la clé (strPath) contient des valeurs
' "DisplayVersion" ou "DisplayName" et qui ne sont pas être vides
' pour ne pas retourner celles qui n'en contiennent pas.
Dim Ret, strNames, Verif, ind
Verif = False
Ret = objRegistry.EnumValues(ROOT, strPath,strNames, Types)
If (Ret = 0) And (Err.Number = 0) And IsArray(strNames) Then
For ind = LBound(strNames) To UBound(strNames)
If LCase(strNames(ind)) = "displayname" Or LCase(strNames(ind)) = "displayversion" Then
Verif = True
Exit For
ELse
Verif = False
End If
Next
End If
VerifTypes = Verif
End Function
'***************************************************************************************
Function ExtractVersion(Data)
Dim objRegex,Match,Matches
Set objRegex = new RegExp
objRegex.Pattern = "\d{2}\.\d"
objRegex.Global = False
objRegex.IgnoreCase = True
Set Matches = objRegex.Execute(Data)
For Each Match in Matches
ExtractVersion = Match.Value
Next
End Function
'***************************************************************************************
Function GetVersionStringAsArray(ByVal Version)
Dim VersionAll, VersionParts, N
VersionAll = Array(0, 0, 0, 0)
VersionParts = Split(Version, ".")
For N = 0 To UBound(VersionParts)
VersionAll(N) = CLng(VersionParts(N))
Next
Dim Hi, Lo
Hi = Lsh(VersionAll(0), 16) + VersionAll(1)
Lo = Lsh(VersionAll(2), 16) + VersionAll(3)
GetVersionStringAsArray = Array(Hi, Lo)
End Function
'***************************************************************************************
' Compares two versions "a.b.c.d". If Version1 < Version2,
' returns -1. If Version1 = Version2, returns 0.
' If Version1 > Version2, returns 1.
Function CompareVersions(ByVal Version1, ByVal Version2)
Dim Ver1, Ver2, Result
Ver1 = GetVersionStringAsArray(Version1)
Ver2 = GetVersionStringAsArray(Version2)
If Ver1(0) < Ver2(0) Then
Result = -1
ElseIf Ver1(0) = Ver2(0) Then
If Ver1(1) < Ver2(1) Then
Result = -1
ElseIf Ver1(1) = Ver2(1) Then
Result = 0
Else
Result = 1
End If
Else
Result = 1
End If
CompareVersions = Result
End Function
'***************************************************************************************
Function GetFirefoxMajorVersion(URL)
Dim Titre,ie,objFSO,Data,OutPut,objRegex,Match,Matches
Titre = "La dernière version de Firefox"
Set ie = CreateObject("InternetExplorer.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
ie.Navigate(URL)
ie.Visible=False
DO WHILE ie.busy
Wscript.Sleep 100
Loop
Data = ie.document.documentElement.innerHTML
Set objRegex = new RegExp
objRegex.Pattern = "\d{2}\.\d"
objRegex.Global = True
objRegex.IgnoreCase = True
Set Matches = objRegex.Execute(Data)
For Each Match in Matches
GetFirefoxMajorVersion = Match.Value
Next
ie.Quit
Set ie = Nothing
End Function
'***************************************************************************************
Here is another way to get FileVersion of Firefox.exe using Powershell and Vbscript
GetFileDetailsFirefox.vbs
Option Explicit
Dim MyCmd,Ws,Ret,ByPassPSFile,PSFile,PathFile,OutPut
Set Ws = CreateObject("wscript.Shell")
PathFile = Ws.ExpandEnvironmentStrings("%ProgramFiles%") & "\Mozilla Firefox\Firefox.exe"
OutPut = Ws.ExpandEnvironmentStrings("%Temp%") & "\firefox_version.txt"
PSFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
ByPassPSFile = "cmd /c PowerShell.exe -ExecutionPolicy bypass -noprofile -file "
MyCmd = "Get-ChildItem "& DblQuote(PathFile) &" | Get-ItemProperty | Select VersionInfo | Format-List > " & OutPut &""
Call WriteLog(MyCmd)
Ret = Ws.run(ByPassPSFile & PSFile,0,True)
ws.run DblQuote(OutPut)
'**********************************************************************************************
Sub WriteLog(strText)
Dim fs,ts,PSFile
Const ForWriting = 2
PSFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'***********************************************************************************************

Keep a VBScript window on top, as well as adding a logoff button

I have a piece of script, courtosey of the user Hackoo, but two things are wrong with it. First, the window needs to stay on top, it shouldn't be able to be exited from the taskbar, it needs to be on the bottom right corner of the screen (above the taskbar) and it needs to have a button on it below the text that says "Log off". Of course, the log off button needs to log off the computer. Here's the code:
Option Explicit
Dim Title,ws,nMinutes,nSeconds,sMessage
Title = "Session Timer"
Set ws = CreateObject("wscript.Shell")
nMinutes = 20
nSeconds = 0
sMessage = "<font color=Red size=2><b>You have"
'Open a chromeless window with message
with HTABox("lightBlue",100,250,0,630)
.document.title = "Session Timer"
.msg.innerHTML = sMessage
do until .done.value or (nMinutes + nSeconds < 1)
.msg.innerHTML = sMessage & "<br>" & nMinutes & ":" & Right("0"&nSeconds, 2) _
& " minutes of session time remaining</b></font><br>"
wsh.sleep 1000 ' milliseconds
nSeconds = nSeconds - 1
if nSeconds < 0 then
if nMinutes > 0 then
nMinutes = nMinutes - 1
nSeconds = 59
end if
end if
loop
.done.value = true
.close
end with
ws.Popup "Your session time has finished. You will now be logged off.","5",Title,0+48
'*****************************************************************
Function HTABox(sBgColor, h, w, l, t)
Dim IE, HTA, sCmd, nRnd
randomize : nRnd = Int(1000000 * rnd)
sCmd = "mshta.exe ""javascript:{new " _
& "ActiveXObject(""InternetExplorer.Application"")" _
& ".PutProperty('" & nRnd & "',window);" _
& "window.resizeTo(" & w & "," & h & ");" _
& "window.moveTo(" & l & "," & t & ")}"""
with CreateObject("WScript.Shell")
.Run sCmd, 1, False
do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop
end with 'WSHShell
For Each IE In CreateObject("Shell.Application").windows
If IsObject(IE.GetProperty(nRnd)) Then
set HTABox = IE.GetProperty(nRnd)
IE.Quit
HTABox.document.title = "HTABox"
HTABox.document.write _
"<HTA:Application contextMenu=no border=thin " _
& "minimizebutton=no maximizebutton=no sysmenu=no SHOWINTASKBAR=no >" _
& "<body scroll=no style='background-color:" _
& sBgColor & ";font:normal 10pt Arial;" _
& "border-Style:inset;border-Width:3px'" _
& "onbeforeunload='vbscript:if not done.value then " _
& "window.event.cancelBubble=true:" _
& "window.event.returnValue=false:" _
& "done.value=true:end if'>" _
& "<input type=hidden id=done value=false>" _
& "<center><span id=msg> </span><br>" _
& "<input type=button id=btn1 value=' OK ' "_
& "onclick=done.value=true><center></body>"
HTABox.btn1.focus
Exit Function
End If
Next
MsgBox "HTA window not found."
wsh.quit
End Function
Thanks,
Matthew
Note that i don't think that we can stay always on the top, but anyway just give a try for this modification, now you want it at the right corner not on the left and i added the button to Logoff the session:
Option Explicit
Dim Title,ws,nMinutes,nSeconds,sMessage,Command,Executer
Title = "Session Timer"
Set ws = CreateObject("wscript.Shell")
nMinutes = 20
nSeconds = 0
sMessage = "<font color=Red size=2><b>You have"
'Open a chromeless window with message
with HTABox("lightBlue",130,300,1070,600)
.document.title = "Session Timer"
.msg.innerHTML = sMessage
do until .done.value or (nMinutes + nSeconds < 1)
.msg.innerHTML = sMessage & "<br>" & nMinutes & ":" & Right("0"&nSeconds, 2) _
& " minutes of session time remaining</b></font><br>"
wsh.sleep 1000 ' milliseconds
nSeconds = nSeconds - 1
if nSeconds < 0 then
if nMinutes > 0 then
nMinutes = nMinutes - 1
nSeconds = 59
end if
end if
loop
.done.value = true
.close
end with
ws.Popup "Your session time has finished. You will now be logged off.","5",Title,0+48
Command ="cmd /c Shutdown.exe -l -f"
Executer = WS.Run(Command,0,False)
'*****************************************************************
Function HTABox(sBgColor,h, w, l, t)
Dim IE, HTA, sCmd, nRnd
randomize : nRnd = Int(1000000 * rnd)
sCmd = "mshta.exe ""javascript:{new " _
& "ActiveXObject(""InternetExplorer.Application"")" _
& ".PutProperty('" & nRnd & "',window);" _
& "window.resizeTo(" & w & "," & h & ");" _
& "window.moveTo(" & l & "," & t & ")}"""
with CreateObject("WScript.Shell")
.Run sCmd, 1, False
do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop
end with 'WSHShell
For Each IE In CreateObject("Shell.Application").windows
If IsObject(IE.GetProperty(nRnd)) Then
set HTABox = IE.GetProperty(nRnd)
IE.Quit
HTABox.document.title = "HTABox"
HTABox.document.write _
"<HTA:Application contextMenu=no border=thin " _
& "minimizebutton=no maximizebutton=no sysmenu=no SHOWINTASKBAR=no >" _
& "<body scroll=no style='background-color:" _
& sBgColor & ";font:normal 10pt Arial;" _
& "border-Style:inset;border-Width:3px'" _
& "onbeforeunload='vbscript:if not done.value then " _
& "window.event.cancelBubble=true:" _
& "window.event.returnValue=false:" _
& "done.value=true:end if'>" _
& "<input type=hidden id=done value=false>" _
& "<center><span id=msg> </span><br>" _
& "<input type=button id=btn1 value=' Log Off ' "_
& "onclick=done.value=true><center></body>"
HTABox.btn1.focus
Exit Function
End If
Next
MsgBox "HTA window not found."
wsh.quit
End Function

VBS function not executing when button is selected

I'm trying to make a VBScript that will allow me to select items from a drop down menu. If possible once an option is selected it will open a particular file or program. I'm not sure why it's not working? Any help would be very much appreciated.
Option Explicit
Dim objShell
Dim aOpt(6)
aOpt(0) = "Option 1"
aOpt(1) = "Option 2"
aOpt(2) = "Option 3"
aOpt(3) = "Option 4"
aOpt(4) = "Option 5"
aOpt(5) = " "
aOpt(6) = " "
SelectBox "Select an install option", aOpt
Function SelectBox(sTitle, aOptions)
Dim oIE, s, item
set oIE = CreateObject("InternetExplorer.Application")
With oIE
.ToolBar = False : .RegisterAsDropTarget = False
.StatusBar = False : .Navigate("about:blank")
While .Busy : WScript.Sleep 100 : Wend
With .document
With .parentWindow
if Instr(.navigator.appVersion, "MSIE 6") > 0 Then
oIE.FullScreen = True
End if
oIE.width = 400 : oIE.height = 600
oIE.left = .screen.width \ 2 - 200
oIE.top = .screen.height\ 2 - 75
End With ' ParentWindow
s = "<html><head><title>" & sTitle & " " & String(80, ".") _
& "</title></head><script language=vbs>bWait=true</script>" _
& "<body bgColor=Silver><center><b>" & sTitle & "<b><p>" _
& "<select id=entries size=1 style='width:250px'>" _
& " <option selected>" & sTitle & "</option>"
For each item in aOptions
s = s & " <option>" & item & "</option>"
Next
s = s & " </select><p>" _
& "<button id=but0 onclick='bWait=false'>OK</button>" _
& "</center></body></html>"
.WriteLn(s)
With .body
.scroll="no"
.style.borderStyle = "outset"
.style.borderWidth = "3px"
End With ' Body
.all.entries.focus
oIE.Visible = True
On Error Resume Next
While .ParentWindow.bWait
WScript.Sleep 100
if oIE.Visible Then SelectBox = ""
if Err Then Exit Function
Wend ' Wait
On Error Goto 0
With .ParentWindow.entries
SelectBox = .options(.selectedIndex).text
End With
End With ' document
.Visible = False
End With ' IE
Set objShell = WScript.CreateObject( "WScript.shell" )
If aOptions = aOpt(0) Then
objShell.Run("""Z:\folder\file""")
Set objShell = Nothing
End if
End Function
"It's not working" because
If aOptions = aOpt(0) Then
compares an array against an element of an other (?) array. By rights you should get an error message:
>> aOptions = Array()
>> If aOptions = "whatever" Then
>> WScript.Echo "bingo"
>> End If
>>
Error Number: 13
Error Description: Type mismatch
If not, you have disabled VBScript's error handling.

Deduplication and filtering of Add/Remove Programs list (VBScript)

This script works and tells and me what is installed in Program files.
Two problems
Duplicate lines
i.e
AVG 2011 Ver: 10.0.1204
AVG 2011 Ver: 10.0.1204 Installed: 27/01/2011
and
I don't want to include lines that have key words "Update","Hotfix","Java" can any VB gurus out there help with what extra is needed in this script?
Option Explicit
Dim sTitle
sTitle = "Installed Programs on your PC -"
Dim StrComputer
strComputer = Trim(strComputer)
If strComputer = "" Then strComputer = "."
'Wscript.Echo GetAddRemove(strComputer)
Dim sCompName : sCompName = GetProbedID(StrComputer)
Dim sFileName
sFileName = sCompName & "_" & GetDTFileName() & "_Software.txt"
Dim s : s = GetAddRemove(strComputer)
If WriteFile(s, sFileName) Then
'optional prompt for display
If MsgBox("Finished processing. Results saved to " & sFileName & _
vbcrlf & vbcrlf & "Do you want to view the results now?", _
4 + 32, sTitle) = 6 Then
WScript.CreateObject("WScript.Shell").Run sFileName, 9
End If
End If
Function GetAddRemove(sComp)
'Function credit to Torgeir Bakken
Dim cnt, oReg, sBaseKey, iRC, aSubKeys
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
sComp & "/root/default:StdRegProv")
sBaseKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
iRC = oReg.EnumKey(HKLM, sBaseKey, aSubKeys)
Dim sKey, sValue, sTmp, sVersion, sDateValue, sYr, sMth, sDay
For Each sKey In aSubKeys
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, "DisplayName", sValue)
If iRC <> 0 Then
oReg.GetStringValue HKLM, sBaseKey & sKey, "QuietDisplayName", sValue
End If
If sValue <> "" Then
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"DisplayVersion", sVersion)
If sVersion <> "" Then
sValue = sValue & vbTab & "Ver: " & sVersion
Else
sValue = sValue & vbTab
End If
iRC = oReg.GetStringValue(HKLM, sBaseKey & sKey, _
"InstallDate", sDateValue)
If sDateValue <> "" Then
sYr = Left(sDateValue, 4)
sMth = Mid(sDateValue, 5, 2)
sDay = Right(sDateValue, 2)
'some Registry entries have improper date format
On Error Resume Next
sDateValue = DateSerial(sYr, sMth, sDay)
On Error GoTo 0
If sdateValue <> "" Then
sValue = sValue & vbTab & "Installed: " & sDateValue
End If
End If
sTmp = sTmp & sValue & vbcrlf
cnt = cnt + 1
End If
Next
sTmp = BubbleSort(sTmp)
GetAddRemove = "INSTALLED SOFTWARE (" & cnt & ") - " & sCompName & _
" - " & Now() & vbcrlf & vbcrlf & sTmp
End Function
Function BubbleSort(sTmp)
'cheapo bubble sort
Dim aTmp, i, j, temp
aTmp = Split(sTmp, vbcrlf)
For i = UBound(aTmp) - 1 To 0 Step -1
For j = 0 to i - 1
If LCase(aTmp(j)) > LCase(aTmp(j+1)) Then
temp = aTmp(j + 1)
aTmp(j + 1) = aTmp(j)
aTmp(j) = temp
End if
Next
Next
BubbleSort = Join(aTmp, vbcrlf)
End Function
Function GetProbedID(sComp)
Dim objWMIService, colItems, objItem
Set objWMIService = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select SystemName from " & _
"Win32_NetworkAdapter",,48)
For Each objItem in colItems
GetProbedID = objItem.SystemName
Next
End Function
Function GetDTFileName()
dim sNow, sMth, sDay, sYr, sHr, sMin, sSec
sNow = Now
sMth = Right("0" & Month(sNow), 2)
sDay = Right("0" & Day(sNow), 2)
sYr = Right("00" & Year(sNow), 4)
sHr = Right("0" & Hour(sNow), 2)
sMin = Right("0" & Minute(sNow), 2)
sSec = Right("0" & Second(sNow), 2)
GetDTFileName = sMth & sDay & sYr & "_" & sHr & sMin & sSec
End Function
Function WriteFile(sData, sFileName)
Dim fso, OutFile, bWrite
bWrite = True
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set OutFile = fso.OpenTextFile(sFileName, 2, True)
'Possibly need a prompt to close the file and one recursion attempt.
If Err = 70 Then
Wscript.Echo "Could not write to file " & sFileName & ", results " & _
"not saved." & vbcrlf & vbcrlf & "This is probably " & _
"because the file is already open."
bWrite = False
ElseIf Err Then
WScript.Echo err & vbcrlf & err.description
bWrite = False
End If
On Error GoTo 0
If bWrite Then
OutFile.WriteLine(sData)
OutFile.Close
End If
Set fso = Nothing
Set OutFile = Nothing
WriteFile = bWrite
End Function
#icecurtain: The second part of your question can be solved using InStr as suggested by #Oliver, rewritten to suit your script it would look like --
If sValue <> "" _
AND (InStr(1, sValue, "Hotfix", 1)) = 0 _
AND (InStr(1, sValue, "Update", 1)) = 0 _
AND (InStr(1, sValue, "Java", 1)) = 0) Then
The first part wouldn't be that tricky either except for the fact that you include a version and installation date if found (which some of the duplicates will only include in part or not at all). If the extra bits of data wasn't included, you could loop through all the lines and add them into a Scripting.Dictory object with a .Exists check to prevent a duplicate from being added.
Ok, even if i'm not a jedi master (or have no self-respect ;-)), this could help you:
If InStr(1, sValue, "hotfix", vbTextCompare) = 0 Then
Print "This is NOT a hotfix"
End If
For further informations just take a look at the MSDN page for InStr().
I don't think hardcoded string checks are the way to go, a uninstall entry is a update if any of these are true:
It has a dword value named SystemComponent that is <> 0
A string value named ParentKeyName
The registry sub key starts with "KB" or "Q" + 6 numbers (KB######,Q######)

Resources