File not found when executing script as admin - vbscript

I have this script that launches an HTA which needs to be started with admin rights.
Set objShell = CreateObject("Wscript.Shell")
isLocal = MsgBox("Launch app for a local configuration ?", vbYesNo + vbQuestion, "Settings")
If isLocal = vbYes Then
objShell.Run "src\Configurator.hta"
Else
'This code doesn't matter here
End If
This script runs fine when started normally, but when I execute the VBS as Administrator (via context menu), I get a File Not Found error for the objShell.Run "src\Configurator.hta" line.
When I add the following code, it gives the same result for both executionning methods (gives the directory where the script is executed).
scriptdir = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)
MsgBox scriptdir
Any help or explanation on this issue would be greatly appreciated.

You can take a look at this : Procedure to run HTA elevated
<html>
<head>
<title>HTA Helpomatic</title>
<HTA:APPLICATION
ID="oHTA"
APPLICATIONNAME="HTAHelpomatic"
SCROLL="yes"
SINGLEINSTANCE="yes"
>
<!-- ID="objHTAHelpomatic" -->
<!-- WINDOWSTATE="maximize" -->
</head>
<SCRIPT Language="VBScript">
If HTAElevate() = True Then
CreateObject("WScript.Shell").Run "mmc.exe compmgmt.msc", , True
Call Main()
End If
Sub Main()
MsgBox "HTA-Ende", 4096
End Sub
'*** v13.3 *** www.dieseyer.de *****************************
Function HTAElevate()
'***********************************************************
' Unter Windows x64 laufen VBS' nach einem Doppelklick in der x64-Umgebung
' mit %WinDi%\System32\wscript.exe oder mit %WinDi%\System32\cscript.exe.
' In der x64-Umgebung laufen VBS aber nicht (richtig). Die Prozedur
' HTAElevate() erkennt dies und startet ggf. das VBS in der
Const Elev = " /elevated"
' MsgBox oHTA.commandLine, , "5016 :: "
' Trace32Log "5018 :: oHTA.commandLine: ==" & oHTA.commandLine & "==", 1
HTAElevate = True
' If InStr( LCase( oHTA.commandLine ), Elev) > 0 then MsgBox oHTA.commandLine, , "5022 :: "
If InStr( LCase( oHTA.commandLine ), Elev) > 0 then Exit Function
On Error Resume Next
window.resizeto 750, 10 ' : window.moveto screen.width / 2, screen.height / 2
On Error GoTo 0
' MsgBox oHTA.commandLine, , "5030 :: "
createobject("Shell.Application").ShellExecute "mshta.exe", oHTA.commandLine & Elev, "", "runas", 1
HTAElevate = False
self.close
End Function ' HTAElevate()
</SCRIPT>
<body>
</body>
</html>

Related

VBScript, HTA - INI Parsing, allow inline comments

I am currently working on a game launcher and have working code borrowed from the Internet to be able to parse an INI. All is working excellently save for one issue.
It cannot parse inline comments on the ini file.
Example:
[Window]
Width=800
Is parsed fine and without issue, great.
[Window]
Width=800 ; width in pixels
But the above is not, I need it to be able to stop reading the line at detecting a ; if possible.
Here is my full HTA code:
<Html>
<Head>
<Title>Installer</Title>
<Meta Http-Equiv="x-ua-compatible" Content="ie=9">
<Link Rel="stylesheet" Type="text/css" Href="image/appStyles.css" Media="screen" />
<Script Language="VBScript" Type="Text/VBScript">
'-- Scripts to be carried out before the installer loads in.
'-- Functions --'
Function ReadIni( myFilePath, mySection, myKey )
' This function returns a value read from an INI file
' Examples
' ReadIni( "settings.config", "Section1", "Keyname1" )
' ReadIni( "settings.config", "Section1", "Keyname2" )
' ReadIni( "settings.config", "Section2", "Keyname1" )
' ReadIni( "settings.config", "Section4", "Keyname2" )
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Dim intEqualPos
Dim objFSO, objIniFile
Dim strFilePath, strKey, strLeftString, strLine, strSection
Set objFSO = CreateObject( "Scripting.FileSystemObject" )
ReadIni = ""
strFilePath = Trim( myFilePath )
strSection = Trim( mySection )
strKey = Trim( myKey )
If objFSO.FileExists( strFilePath ) Then
Set objIniFile = objFSO.OpenTextFile( strFilePath, ForReading, False )
Do While objIniFile.AtEndOfStream = False
strLine = Trim( objIniFile.ReadLine )
' Check if section is found in the current line
If LCase( strLine ) = "[" & LCase( strSection ) & "]" Then
strLine = Trim( objIniFile.ReadLine )
' Parse lines until the next section is reached
Do While Left( strLine, 1 ) <> "["
' Find position of equal sign in the line
intEqualPos = InStr( 1, strLine, "=", 1 )
If intEqualPos > 0 Then
strLeftString = Trim( Left( strLine, intEqualPos - 1 ) )
' Check if item is found in the current line
If LCase( strLeftString ) = LCase( strKey ) Then
ReadIni = Trim( Mid( strLine, intEqualPos + 1 ) )
' In case the item exists but value is blank
If ReadIni = "" Then
ReadIni = " "
End If
' Abort loop when item is found
Exit Do
End If
End If
' Abort if the end of the INI file is reached
If objIniFile.AtEndOfStream Then Exit Do
' Continue with next line
strLine = Trim( objIniFile.ReadLine )
Loop
Exit Do
End If
Loop
objIniFile.Close
Else
' WScript.Echo strFilePath & " doesn't exists. Exiting..."
' Wscript.Quit 1
End If
End Function
'-- Subroutines --'
'-- Resize & move app to center
Sub SetWindow( WidthX,HeightY )
Self.ResizeTo WidthX, HeightY
Self.MoveTo (screen.Width - WidthX)/2, (screen.Height - HeightY)/2
End Sub
'-- Close app
Sub WinClose
Self.Close
End Sub
'-- Startup --'
'-- Read the configuration settings.
IniFile = "settings.config"
WinWidth = ReadIni( IniFile, "Window", "Width" )
WinHeight = ReadIni( IniFile, "Window", "Height" )
'-- Set Window size
SetWindow WinWidth, WinHeight
</Script>
<Hta:Application Id="Installer" ApplicationName="Installer" Version="0.1"
SingleInstance="Yes"
Icon="image/appIcon.ico"
Caption="No"
Border="None"
InnerBorder="No"
ContextMenu="No"
SysMenu="None"
Scroll="No"
Selection="No"
/>
</Head>
<Body>
<Div Id="status">Hello</Div>
<Script Language="VBScript" Type="Text/VBScript">
'-- Scripts that require access to the DOM...
'-- Startup
document.getElementById("status").InnerHTML = "Idle"
document.title = ReadIni( IniFile, "App", "Title" )
</Script>
<Script Type="Text/Javascript">
//-- Javascripts that require access to the DOM...
window.onload = function() {
var a = document.getElementsByTagName("img");
a.ondragstart = function() { return false; }
}
</Script>
</Body>
</Html>
Any help you guys could provide would be great, thank you!
WinWidth = Trim(Split(ReadIni( IniFile, "Window", "Width" ), ";")(0))
Split the value using the semicolon, take the first element in the list and remove start/end spaces if present

Restarting HTA?

I'm looking for a bit of code to get an HTA to restart from the beginning. I have seen a forum on this site that creates an HTA that calls a .vbs and cyclically restarts, but I'm looking for hopefully a line or 5 or code that will start an HTA from the beginning.
What I could do is have the script re-open the HTA with the shell.run command and then close it, but is there a cleaner way to do this?
Here is a complete example showing how we can use Location.Reload(True) to reload the HTA file
The good password is 9999
<HTML>
<HEAD>
<TITLE></TITLE>
<HTA:APPLICATION
APPLICATIONNAME="Access to the system © Hackoo © 2015"
BORDER="THIN"
BORDERSTYLE="NORMAL"
ICON="Explorer.exe"
INNERBORDER="NO"
MAXIMIZEBUTTON="NO"
MINIMIZEBUTTON="NO"
SCROLL="NO"
SELECTION="NO"
SINGLEINSTANCE="YES"/>
</HEAD>
<META HTTP-EQUIV="MSThemeCompatible" CONTENT="YES">
<BODY TOPMARGIN="1" LEFTMARGIN="1"><CENTER><DIV><SPAN ID="ONSCR"></SPAN></DIV></CENTER></BODY>
<SCRIPT LANGUAGE="VBScript">
Option Explicit
Dim Title,ws,Voice,ErrorMsg,WelcomeMsg,MyGoodPassword,Password,Temp,Tests,ProcessEnv,UserName
Title = "Access to the system © Hackoo 2015"
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("wscript.Shell")
Set ProcessEnv = Ws.Environment("Process")
UserName = ProcessEnv("USERNAME")
Temp = WS.ExpandEnvironmentStrings("%Temp%")
Tests = Temp &"\Tests.txt"
'------------------------------------------------------------------------------------
Sub window_onload()
CenterWindow 280,180
Call PasswordForm()
Call TextFocus
Dim Count : Count = 0
If Not objFSO.FileExists(Tests) Then
Dim Logfile : Set Logfile = objFSO.OpenTextFile(Tests,2,True)
Logfile.writeline Count
Logfile.Close
end If
Call Kill("Explorer.exe")
Call DisableTaskMgr()
End Sub
'------------------------------------------------------------------------------------
Sub CenterWindow(x,y)
Dim iLeft,itop
window.resizeTo x,y
iLeft = window.screen.availWidth/2 - x/2
itop = window.screen.availHeight/2 - y/2
window.moveTo ileft,itop
End Sub
'------------------------------------------------------------------------------------
Sub PasswordForm()
Self.document.title = "Access to the system © Hackoo 2015"
Self.document.bgColor = "DarkOrange"
ONSCR.InnerHTML="<center><FONT COLOR=""#FFFFFF"" SIZE=""+1"" FACE=""VERDANA,ARIAL,HELVETICA,SANS-SERIF"">Type your Password</FONT><br><br><input type=""password"" name=""PasswordArea"" size=""20"" onKeyUp=""TextFocus""><P>"_
&"<input type=""Submit"" STYLE=""HEIGHT:25;WIDTH:190"" value=""Access to the system"" name=""run_button"" onClick=""CheckPassword"">"
END Sub
'------------------------------------------------------------------------------------
Sub CheckPassword
Dim NB_Tests_MAX : NB_Tests_MAX = 3
Dim Readfile,Count,NB_Tests_Remaining,Logfile,Controle,Command,Executer,MsgNumbTests,MsgReboot
Set Voice = CreateObject("SAPI.SpVoice")
ErrorMsg = "ATTENTION ! ! ! "& vbcr &"The Password is Wrong ! "& vbcr &"Try Again !"
WelcomeMsg = "Welcome again "& DblQuote(UserName) &" in your System !"
MyGoodPassword = "9999"
Set Readfile = objFSO.OpenTextFile(Tests,1)
Count = Readfile.ReadAll
Readfile.Close
Controle = True
While Controle
Count = Count + 1
NB_Tests_Remaining = NB_Tests_MAX - Count
Set Logfile = objFSO.OpenTextFile(Tests,2,True)
Logfile.writeline Count
Logfile.Close
If PasswordArea.Value <> MyGoodPassword Then
Voice.Speak ErrorMsg
ws.Popup ErrorMsg,"1",Title,0+16
MsgNumbTests = "ATTENTION !!! "&vbcr&"Bad Password and NB°of TESTS is " & Count &"."&vbCr&_
"The remaining number of tests is "& NB_Tests_Remaining
Voice.Speak MsgNumbTests
MsgBox MsgNumbTests,48,Title
Sleep(1)
Location.Reload(True)
end if
If PasswordArea.Value = MyGoodPassword Then
If objFSO.FileExists(Tests) Then objFSO.DeleteFile Tests,True
Controle = False
Voice.Speak WelcomeMsg
ws.Popup WelcomeMsg,"1",Title,0+64
Call Launch("Explorer.exe")
Call EnableTaskMgr()
Self.Close
Exit Sub
End If
If Count = NB_Tests_MAX Then
If objFSO.FileExists(Tests) Then objFSO.DeleteFile Tests,True
Voice.Speak "The computer will reboot in 30 seconds !"
MsgReboot = "The Limit number of tests is reached ! "&vbcr& "The computer will Reboot in 30 seconds !"
MsgBox MsgReboot,48,"The Limit number of tests is reached ! "
Command="cmd /c Shutdown.exe -r -t 30 -c " & chr(34) & "The computer will reboot in 30 seconds !" & chr(34)
Executer = WS.Run(Command,0,False)
window.close
End If
Exit Sub
wend
End Sub
'----------------------------------------------------------------------------------
Sub TextFocus
PasswordArea.Focus
End Sub
'----------------------------------------------------------------------------------
Sub Kill(Process)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
'----------------------------------------------------------------------------------
Sub Launch(Process)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Start "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
'-----------------------------------------------------------------------------------
'------------------------------EnableTaskMgr----------------------------------------
Sub EnableTaskMgr()
Dim WshShell,System
System="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\"
Set WshShell=CreateObject("WScript.Shell")
Wshshell.RegWrite System, "REG_SZ"
WshShell.RegWrite System &"\DisableTaskMgr", 0, "REG_DWORD"
End sub
'------------------------------------------------------------------------------------
'-----------------------------DisableTaskMgr-----------------------------------------
Sub DisableTaskMgr()
Dim WshShell,System
System="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\"
Set WshShell=CreateObject("WScript.Shell")
Wshshell.RegWrite System, "REG_SZ"
WshShell.RegWrite System &"\DisableTaskMgr", 1, "REG_DWORD"
End sub
'--------------------------------------------------------------------------------------
Sub Sleep(intNumSecs)
' Because WScript.Sleep () is not available in HTA
' scripts, invoke a VBScript file to do the waiting.
Dim strScriptFile, strCommand, intRetcode, objWS
If intNumSecs <= 0 Then Exit Sub
Set objWS = CreateObject ("WScript.Shell")
strScriptFile = "%temp%\wait" & intNumSecs & "seconds.vbs"
strCommand = "cmd /c ""echo WScript.Sleep " & intNumSecs * 1000 & " >" & strScriptFile & _
"&start /wait """" wscript.exe " & strScriptFile & """"
intRetCode = objWS.Run (strCommand, 0, True)
If intRetCode = 0 Then Exit Sub
End Sub
'---------------------------------------------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'---------------------------------------------------------------------------------------
</SCRIPT>
In referring to a comment by #MCND, to restart a script, simply implement
location.reload True
After whatever event you want to use

Require a Password to close an HTA

I was hoping someone would be able to proved me some direction. I would like to set an application launcher I have created to require a password to be closed. Thank you for any assistance you are able to offer.
But here is some incomplete code to show you my purpose.
Set objShell = CreateObject("Wscript.Shell")
dim password
password=InputBox("Please Enter Password:","3 - Tries Left")
if password = ("9999") then
dim correct correct =MsgBox("Correct Password!",64,"correct")
objShell.Run("shutdown /m shutdown -r -f -t 0")
Else
dim again
again =MsgBox("Incorrect Password! Do You Want To Try Again?",53,"Incorrect Password!")
If again = 4 Then
dim password2
password2=InputBox("Please Enter Password:","2 - Tries Left")
if password2 = ("9999") then
dim correct2
correct2 =MsgBox("Correct Password!",64,"correct")
Sorry ! I was unable to post all of the code.I just need to know what to put to close the existing window. I think telling it to close MSHTA.EXE will work.
Try this HTA and i hope that can did the trick.
NB : The Password is 9999 and of course you can change it at this line
MyGoodPassword = "9999"
<HTML>
<HEAD>
<TITLE></TITLE>
<HTA:APPLICATION
APPLICATIONNAME="Access to the system © Hackoo © 2015"
BORDER="THIN"
BORDERSTYLE="NORMAL"
ICON="Explorer.exe"
INNERBORDER="NO"
MAXIMIZEBUTTON="NO"
MINIMIZEBUTTON="NO"
SCROLL="NO"
SELECTION="NO"
SINGLEINSTANCE="YES"/>
</HEAD>
<META HTTP-EQUIV="MSThemeCompatible" CONTENT="YES">
<BODY TOPMARGIN="1" LEFTMARGIN="1"><CENTER><DIV><SPAN ID="ONSCR"></SPAN></DIV></CENTER></BODY>
<SCRIPT LANGUAGE="VBScript">
Option Explicit
Dim Title,ws,Voice,ErrorMsg,WelcomeMsg,MyGoodPassword,Password,Temp,Tests,ProcessEnv,UserName
Title = "Access to the system © Hackoo 2015"
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject")
Set ws = CreateObject("wscript.Shell")
Set ProcessEnv = Ws.Environment("Process")
UserName = ProcessEnv("USERNAME")
Temp = WS.ExpandEnvironmentStrings("%Temp%")
Tests = Temp &"\Tests.txt"
'------------------------------------------------------------------------------------
Sub window_onload()
CenterWindow 280,180
Call PasswordForm()
Call TextFocus
Dim Count : Count = 0
If Not objFSO.FileExists(Tests) Then
Dim Logfile : Set Logfile = objFSO.OpenTextFile(Tests,2,True)
Logfile.writeline Count
Logfile.Close
end If
Call Kill("Explorer.exe")
Call DisableTaskMgr()
End Sub
'------------------------------------------------------------------------------------
Sub CenterWindow(x,y)
Dim iLeft,itop
window.resizeTo x,y
iLeft = window.screen.availWidth/2 - x/2
itop = window.screen.availHeight/2 - y/2
window.moveTo ileft,itop
End Sub
'------------------------------------------------------------------------------------
Sub PasswordForm()
Self.document.title = "Access to the system © Hackoo 2015"
Self.document.bgColor = "DarkOrange"
ONSCR.InnerHTML="<center><FONT COLOR=""#FFFFFF"" SIZE=""+1"" FACE=""VERDANA,ARIAL,HELVETICA,SANS-SERIF"">Type your Password</FONT><br><br><input type=""password"" name=""PasswordArea"" size=""20"" onKeyUp=""TextFocus""><P>"_
&"<input type=""Submit"" STYLE=""HEIGHT:25;WIDTH:190"" value=""Access to the system"" name=""run_button"" onClick=""CheckPassword"">"
END Sub
'------------------------------------------------------------------------------------
Sub CheckPassword
Dim NB_Tests_MAX : NB_Tests_MAX = 3
Dim Readfile,Count,NB_Tests_Remaining,Logfile,Controle,Command,Executer,MsgNumbTests,MsgReboot
Set Voice = CreateObject("SAPI.SpVoice")
ErrorMsg = "ATTENTION ! ! ! "& vbcr &"The Password is Wrong ! "& vbcr &"Try Again !"
WelcomeMsg = "Welcome again "& DblQuote(UserName) &" in your System !"
MyGoodPassword = "9999"
Set Readfile = objFSO.OpenTextFile(Tests,1)
Count = Readfile.ReadAll
Readfile.Close
Controle = True
While Controle
Count = Count + 1
NB_Tests_Remaining = NB_Tests_MAX - Count
Set Logfile = objFSO.OpenTextFile(Tests,2,True)
Logfile.writeline Count
Logfile.Close
If PasswordArea.Value <> MyGoodPassword Then
Voice.Speak ErrorMsg
ws.Popup ErrorMsg,"1",Title,0+16
MsgNumbTests = "ATTENTION !!! "&vbcr&"Bad Password and NB°of TESTS is " & Count &"."&vbCr&_
"The remaining number of tests is "& NB_Tests_Remaining
Voice.Speak MsgNumbTests
MsgBox MsgNumbTests,48,Title
Sleep(1)
Location.Reload(True)
end if
If PasswordArea.Value = MyGoodPassword Then
If objFSO.FileExists(Tests) Then objFSO.DeleteFile Tests,True
Controle = False
Voice.Speak WelcomeMsg
ws.Popup WelcomeMsg,"1",Title,0+64
Call Launch("Explorer.exe")
Call EnableTaskMgr()
Self.Close
Exit Sub
End If
If Count = NB_Tests_MAX Then
If objFSO.FileExists(Tests) Then objFSO.DeleteFile Tests,True
Voice.Speak "The computer will reboot in 30 seconds !"
MsgReboot = "The Limit number of tests is reached ! "&vbcr& "The computer will Reboot in 30 seconds !"
MsgBox MsgReboot,48,"The Limit number of tests is reached ! "
Command="cmd /c Shutdown.exe -r -t 30 -c " & chr(34) & "The computer will reboot in 30 seconds !" & chr(34)
Executer = WS.Run(Command,0,False)
window.close
End If
Exit Sub
wend
End Sub
'----------------------------------------------------------------------------------
Sub TextFocus
PasswordArea.Focus
End Sub
'----------------------------------------------------------------------------------
Sub Kill(Process)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Taskkill /F /IM "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
'----------------------------------------------------------------------------------
Sub Launch(Process)
Dim Ws,Command,Execution
Set Ws = CreateObject("Wscript.Shell")
Command = "cmd /c Start "&Process&""
Execution = Ws.Run(Command,0,False)
End Sub
'-----------------------------------------------------------------------------------
'------------------------------EnableTaskMgr----------------------------------------
Sub EnableTaskMgr()
Dim WshShell,System
System="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\"
Set WshShell=CreateObject("WScript.Shell")
Wshshell.RegWrite System, "REG_SZ"
WshShell.RegWrite System &"\DisableTaskMgr", 0, "REG_DWORD"
End sub
'------------------------------------------------------------------------------------
'-----------------------------DisableTaskMgr-----------------------------------------
Sub DisableTaskMgr()
Dim WshShell,System
System="HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Policies\System\"
Set WshShell=CreateObject("WScript.Shell")
Wshshell.RegWrite System, "REG_SZ"
WshShell.RegWrite System &"\DisableTaskMgr", 1, "REG_DWORD"
End sub
'--------------------------------------------------------------------------------------
Sub Sleep(intNumSecs)
' Because WScript.Sleep () is not available in HTA
' scripts, invoke a VBScript file to do the waiting.
Dim strScriptFile, strCommand, intRetcode, objWS
If intNumSecs <= 0 Then Exit Sub
Set objWS = CreateObject ("WScript.Shell")
strScriptFile = "%temp%\wait" & intNumSecs & "seconds.vbs"
strCommand = "cmd /c ""echo WScript.Sleep " & intNumSecs * 1000 & " >" & strScriptFile & _
"&start /wait """" wscript.exe " & strScriptFile & """"
intRetCode = objWS.Run (strCommand, 0, True)
If intRetCode = 0 Then Exit Sub
End Sub
'---------------------------------------------------------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'---------------------------------------------------------------------------------------
</SCRIPT>

MSGbox in VBS that updates with value of variable

Just wondering how i could have a MSgbox that displays the value of a variable as it constantly changes. Basically a number has one added to it everytime it loops. I want to display that in a MSGbox that doesnt have to open a million windows
A workaround would be to use PopUp
Set objShell = WScript.CreateObject("WScript.Shell")
For i = 1 To 3
objShell.Popup i, 1, "AutoClose MsgBox Simulation", vbInformation+vbOKOnly
Next
This will "autoclose" the MsgBox lookalike after 1 second
You can't do this with the default VBScript dialog elements, like MsgBox, WScript.Echo or Popup. You need to build a custom dialog using the Internet Explorer COM object:
Set ie = CreateObject("InternetExplorer.Application")
ie.Navigate "about:blank"
While ie.ReadyState <> 4 : WScript.Sleep 100 : Wend
ie.ToolBar = False
ie.StatusBar = False
ie.Width = 300
ie.Height = 200
ie.document.body.innerHTML = "<p id='msg'>0</p>"
Set style = ie.document.CreateStyleSheet
style.AddRule "p", "text-align: center;"
ie.Visible = True
i = 1
Do
ie.document.getElementById("msg").innerText = i
i = i + 1
WScript.Sleep 2000
Loop Until i > 10
or use an HTA instead of plain VBScript:
<head>
<title>Test</title>
<HTA:APPLICATION ID="oHTA"
APPLICATIONNAME="Test"
SCROLL="no"
>
</head>
<style type="text/css">
p {text-align: center;}
</style>
<script language="VBScript">
window.resizeTo 300, 200
Set sh = CreateObject("WScript.Shell")
Sub Window_onLoad
For i = 1 To 10
msg.innerText = i
Sleep 2
Next
End Sub
Sub Sleep(t)
sh.Run "ping -n " & (t+1) & " 127.0.0.1", 0, True
End Sub
</script>
<body>
<p id="msg">0</p>
</body>
One more solution, uses HTA window, without temp files:
dim window, i
set window = createwindow()
window.document.write "<html><body bgcolor=buttonface>Current loop is: <span id='output'></span></body></html>"
window.document.title = "Processing..."
window.resizeto 300, 150
window.moveto 200, 200
for i = 0 to 32767
show i
' your code here
next
window.close
function show(value)
on error resume next
window.output.innerhtml = value
if err then wscript.quit
end function
function createwindow()
' source http://forum.script-coding.com/viewtopic.php?pid=75356#p75356
dim signature, shellwnd, proc
on error resume next
set createwindow = nothing
signature = left(createobject("Scriptlet.TypeLib").guid, 38)
set proc = createobject("WScript.Shell").exec("mshta about:""<script>moveTo(-32000,-32000);</script><hta:application id=app border=dialog minimizebutton=no maximizebutton=no scroll=no showintaskbar=yes contextmenu=no selection=no innerborder=no /><object id='shellwindow' classid='clsid:8856F961-340A-11D0-A96B-00C04FD705A2'><param name=RegisterAsBrowser value=1></object><script>shellwindow.putproperty('" & signature & "',document.parentWindow);</script>""")
do
if proc.status > 0 then exit function
for each shellwnd in createobject("Shell.Application").windows
set createwindow = shellwnd.getproperty(signature)
if err.number = 0 then exit function
err.clear
next
loop
end function
This script will display how many loops it took and the value of a variable during the loop, and display the results in 1 message box after the loop is complete.
Dim RateOfChange, roc, watchvariable : roc = 1 : watchvariable = 1
for i=1 to 25
watchvariable = (watchvariable * i) * 16
RateOfChange = RateOfChange & "Iteration[" & roc & "]" & " - Value[" & watchvariable & "]" & vbcrlf
roc = roc + 1
next
'NOTE uncomment this below to activate msgbox.
'msgbox rateofchange
wscript.echo rateofchange

How to create a registry key with VBS?

Okay, I will try asking this question again.
I used this code:
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\test", 1, "REG_DWORD"
I get the error 'Invalid root in registry key' Code: 80070005 (Access Denied)
The code works with other registry roots. I am logged on as an administrator. It works when I run it from an elevated command prompt. But I am making this VBS as a prank to a friend to make him not know what I'm doing. Any ideas?
The best way to distribute registry setting is by exporting the part of a registry where this setting is active to a .reg file with the registry editor. In the save part of the export dialog you choose Win9x/NT4 as format. You can check the .reg file with an editor. The user only has to double click the .reg file and confirm the prompt and possibly reboot his pc. Even normal users should be able to do this. If the registrybranch you try to change is protected by security he wil have to do this with admin right and possibly (depenidng on OS version) start regedit with the the regedt32.exe executable and first adapt the security of that branch so that it can be changed.
Doing this with a script means having to pass additional layers of security to make sure this isn't a malicious script.
Sub x86Win32ScriptingElevate()
in WinXP and Win7 - its works fine:
Call x86Win32ScriptingElevate()
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.RegWrite "HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\System\test", 1, "REG_DWORD"
WScript.Quit
'*** v13.3 *** www.dieseyer.de *****************************
Sub x86Win32ScriptingElevate()
'***********************************************************
' http://dieseyer.de/scr/elevate.vbs
' Unter Windows x64 laufen VBS' nach einem Doppelklick in der x64-Umgebung
' mit %WinDi%\System32\wscript.exe oder mit %WinDi%\System32\cscript.exe.
' In der x64-Umgebung laufen VBS aber nicht (richtig). Die Prozedur
' x86Win32ScriptingElevate() erkennt dies und startet ggf. das VBS in der
' x86-Umgebung mit
' %WinDirr%\SysWOW64\wscript.exe bzw. mit
' %WinDirr%\SysWOW64\cscript.exe
Dim VBSExe, Tst, TxtArg, i
' MsgBox WScript.FullName & vbCRLF & vbFalse & "..." & False & vbCRLF & wscript.arguments.named.exists("elevated"), , "173 :: "
If wscript.arguments.named.exists("elevated") = True then Exit Sub
' Argumentte sammeln
Dim Args : Set Args = Wscript.Arguments
For i = 0 to Args.Count - 1 ' hole alle Argumente
TxtArg = TxtArg & " " & Args( i )
Next
TxtArg = Trim( TxtArg )
' MsgBox ">" & TxtArg & "<", , "184 :: "
VBSExe = UCase( WScript.FullName )
' x86- / Win32-Systeme haben KEIN %WinDir%\SysWOW64\ - Verzeichnis
Tst = Replace( VBSExe, "\SYSTEM32\", "\SYSWOW64\" )
If CreateObject("Scripting.FileSystemObject").FileExists( Tst ) Then VBSExe = Tst
' VBS mit /elevate starten - ggf. auf x64-System in Win32-Umgebung
' Msgbox """" & VBSExe & """ """ & WScript.ScriptFullName & """ " & TxtArg , , "196 :: "
Tst = createobject("Shell.Application").ShellExecute( """" & VBSExe & """", """" & wscript.scriptfullname & """ " & TxtArg & " /elevated", "", "runas", 1 )
WScript.Quit( Tst )
End Sub ' x86Win32ScriptingElevate()

Resources