reading a text file after executing a batch file through VBScript - batch-file

I have to execute a batch file using run and get the output in a text file and search that file for a string the code snippet as below,
For running the bat file
Set objShell = WScript.CreateObject("WScript.Shell")
MsgBox("Compiling Source files..Please wait..")
objShell.Run CHR(34) & ".\lib\Compile.bat" & CHR(34) & " > compile.txt" & CHR(34), 0 ,True
I found out that the execution is not going to the next line after run, but if i end process of cmd.exe in task manager the execution happens.
I have mentioned true to wait for the process to get complete after this am reading like below,
Dim objFSO, strLine, objReadFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objReadFile = objFSO.OpenTextFile("./compile.txt", 1 , true)
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
....
....
How ever the compile.bat is executing and compile.txt is getting created but the reading process doesn't happen. If i remove the "true" from run command am getting "compile.txt file doesn't exist" error.
I don't know where am making mistake please help me with it..

From all your questions I assume the the story behind your problem
goes something like this:
Your boss, Mr. D. Vader, asked you to develop the build system for
his Java application. "Ok", you said, "let's use Eclipse and/or Ant."
"No", said Mr. Vader, "we will have a modern BS with .BATs and one
button GUIs".
So you set up an experimental project:
tree /a /f .
E:\TRIALS\SOTRIALS\ANSWERS\19944721
|
+---vbs
| | javacompile.hta
| | javacompile.vbs
|
\---java
+---good
| Good.java
|
\---bad
Bad.java
Starting with a minimal Good.java:
class Good {
public static void main(String[] args) {
System.out.println("use Eclipse!");
}
}
you verified:
javac Good.java
- no news are good news --
echo %ERRORLEVEL%
0 <-- javac may set ERRORLEVEL
java Good
use Eclipse! <-- it works
Same procedure for the bad:
class Bad {
public static void main(String[] args) {
System.out.println("D. Vader says: 'Use .bat and one button GUI!'.");
}
javac Bad.java
Bad.java:4: reached end of file while parsing
}
^ <-- javac finds the missing }
1 error
echo %ERRORLEVEL%
1 <-- javac really sets ERRORLEVEL
Then you wrote the minimal GUI: javacompile.hta
<html>
<head>
<Title>JavaCompile</Title>
<hta:application id="javacompile" scroll = "no">
<script type="text/vbscript" src="javacompile.vbs"></script>
</head>
<body>
<form>
<input type="button" id="bttCheckBasics" value="Check Basics"/>
<form>
</body>
</html>
and the 'code behind' javacompile.vbs
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
' document.location: "file:///E:/trials/SoTrials/answers/19944721/vbs/javacompile.hta"
Dim gsVbsF : gsVbsF = Replace(goFS.GetParentFolderName(Mid(document.location, 9)), "/", "\")
Dim gsJavaF : gsJavaF = goFS.GetAbsolutePathName(goFS.BuildPath(gsVbsF, "..\java"))
Dim gsGoodF : gsGoodF = goFS.BuildPath(gsJavaF, "good")
Dim gsBadF : gsBadF = goFS.BuildPath(gsJavaF, "bad")
Sub bttCheckBasics_onclick()
MsgBox "Sub bttCheckBasics_onclick() was called."
MsgBox Join(Array("Known Folders:", gsVbsF, gsJavaF, gsGoodF, gsBadF), vbCrLf)
End Sub
and verified that the GUI knows where is what (and the auto-binding works).
(Copy from MessageBox)
Known Folders:
E:\trials\SoTrials\answers\19944721\vbs
E:\trials\SoTrials\answers\19944721\java
E:\trials\SoTrials\answers\19944721\java\good
E:\trials\SoTrials\answers\19944721\java\bad
---------------------------
OK
---------------------------
To get the ball rolling, you added a button to the .hta
<br/>
<input type="button" id="bttKiss" value="Keep It Simple, Stupid"/>
and some code to the vbs:
Sub bttKiss_onclick()
MsgBox "Sub bttKiss_onclick() was called."
KissCompile gsGoodF, "Good.java", "bgood.bat"
KissCompile gsBadF, "Bad.java", "bbat.bat"
End Sub
Sub KissCompile( sF, sJava, sBat)
goWSH.CurrentDirectory = sF
Dim sCmd : sCmd = Join(Array("javac", sJava))
Dim oExec : Set oExec = goWSH.Exec(sCmd)
Do Until cnWshFinished = oExec.Status : Loop
MsgBox Join(Array(qq(sCmd), "(javac) ExitCode:", oExec.ExitCode))
If 0 <> oExec.ExitCode Then MsgBox oExec.StdErr.ReadAll(), vbAbortRetryIgnore, "You messed it up, Mr. Vader!"
End Sub
Function qq(s)
qq = """" & s & """"
End Function
Now the GUI shows for two MessageBoxes for the bad case:
---------------------------
"javac Bad.java" (javac) ExitCode: 1
---------------------------
OK
---------------------------
---------------------------
You messed it up, Mr. Vader!
---------------------------
Bad.java:4: reached end of file while parsing
}
^
1 error
---------------------------
Mr. Vader is not amused: Black windows all over the place and not a single .BAT!
Your ingenious trick of setting goWSH.CurrentDirectory does not impress
him at all.
So you wrote bgood.bat:
#echo off
javac Good.java
IF ERRORLEVEL 1 GOTO :bingo
echo SUCCESS
GOTO :end
:bingo
echo FAILURE
:end
and a corresponding bbad.bat. Some tests:
bbad
Bad.java:4: reached end of file while parsing
}
^
1 error
FAILURE
JAVA E:\trials\SoTrials\answers\19944721\java\bad
echo %ERRORLEVEL%
1
Now the story changes to science fiction. You will follow my advice to
use my BTicks function slightly modified for a better handling of directories and minus a bug wrt to the deletion of log files. So util.vbs looks like
Option Explicit
Const cnWshRunning = 0 ' The job is still running.
Const cnWshFinished = 1 ' The job has completed.
Const SW_SHOWMINNOACTIVE = 7
Const ForReading = 1
Function qq(s)
qq = """" & s & """"
End Function
' BTicks - execute sCmd via WSH.Run
' aRet( 0 ) : goWSH.Run() result
' aRet( 1 ) : StdErr / error message
' aRet( 2 ) : StdOut
' aRet( 3 ) : command to run
Function BTicks(sExecF, sLogF, sCmd )
goWSH.CurrentDirectory = sExecF
Dim aRet : aRet = Array(-1, "", "", "")
Dim sFSpec1 : sFSpec1 = goFS.BuildPath(sLogF, goFS.GetTempName() )
Dim sFSpec2 : sFSpec2 = goFS.BuildPath(sLogF, goFS.GetTempName() )
aRet(3) = Join(Array( _
qq("%comspec%") _
, "/c" _
, qq(Join(Array( _
sCmd _
, "1>" & qq(sFSpec1) _
, "2>" & qq(sFSpec2) _
)))))
Dim aErr
On Error Resume Next
aRet(0) = goWSH.Run(aRet( 3 ), SW_SHOWMINNOACTIVE, True)
aErr = Array(Err.Number, Err.Description, Err.Source)
On Error GoTo 0
If 0 <> aErr(0) Then
aRet(0) = aErr(0)
aRet(1) = Join(Array(aErr(1), aErr(2), "(BTicks)"), vbCrLf)
BTicks = aRet
Exit Function
End If
Dim nIdx : nIdx = 1
Dim sFSpec
For Each sFSpec In Array(sFSpec2, sFSpec1)
If goFS.FileExists(sFSpec) Then
Dim oFile : Set oFile = goFS.GetFile(sFSpec)
If 0 < oFile.Size Then
aRet(nIdx) = oFile.OpenAsTextStream(ForReading).ReadAll()
End If
oFile.Delete
End If
nIdx = nIdx + 1
Next
BTicks = aRet
End Function
As this file has to be included and the 'old' buttons aren't needed
anymore, javacompile.hta changes to
<html>
<head>
<Title>JavaCompile</Title>
<hta:application id="javacompile" scroll = "no">
<script type="text/vbscript" src="javacompile.vbs"></script>
<script type="text/vbscript" src="util.vbs"></script>
</head>
<body>
<form>
<input type="button" id="bttBTicks" value="Use BTicks, Stupid"/>
<form>
</body>
</html>
and javacompile.vbs gets shorter too:
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
' document.location: "file:///E:/trials/SoTrials/answers/19944721/vbs/javacompile.hta"
Dim gsVbsF : gsVbsF = Replace(goFS.GetParentFolderName(Mid(document.location, 9)), "/", "\")
Dim gsJavaF : gsJavaF = goFS.GetAbsolutePathName(goFS.BuildPath(gsVbsF, "..\java"))
Dim gsGoodF : gsGoodF = goFS.BuildPath(gsJavaF, "good")
Dim gsBadF : gsBadF = goFS.BuildPath(gsJavaF, "bad")
Dim goWSH : Set goWSH = CreateObject( "WScript.Shell" )
Sub bttBTicks_onclick()
MsgBox "Sub bttUseBTicks_onclick() was called."
Dim aRet
aRet = BTicksCompile(gsGoodF, "javac Good.java")
aRet = BTicksCompile(gsGoodF, "bgood.bat")
aRet = BTicksCompile(gsBadF , "javac Bad.java")
aRet = BTicksCompile(gsBadF , "bbad.bat")
End Sub
Function BTicksCompile(sF, sCmd)
BTicksCompile = BTicks(sF, gsVbsF, sCmd)
MsgBox Join(BTicksCompile, vbCrLf & "--------" & vbCrLf)
End Function
Now there are no more black boxes and the last display (for bbad.bat) shows
the magic word FAILURE.
---------------------------
0
--------
Bad.java:4: reached end of file while parsing
}
^
1 error
--------
FAILURE
--------
"%comspec%" /c "bbad.bat 1>"E:\trials\SoTrials\answers\19944721\vbs\rad6CE21.tmp" 2>"E:\trials\SoTrials\answers\19944721\vbs\radC7CE6.tmp""
---------------------------
OK
---------------------------

Can you specify absolute paths?
If you use the true argument for objFSO.OpenTextFile then it will create the file if it's not found. I can't see why in your case you would want to do that, and this would explain why you are not "reading" the file. If you just created it somewhere, it would be empty.
If you know compile.bat is creating the text file, the next step is to figure out why OpenTextFile isn't finding it. If you use absolute paths, you can quickly resolve this.
If absolute paths are not an option, then use a MsgBox WScript.ScriptFullName or something to verify the path from where the script is running.
You might also do something like this, which would use the relative path of the script's running location
strPath = Replace(WScript.ScriptFullName,WScript.ScriptName,"")
objShell.Run ".\lib\Compile.bat" & " > " & strPath & "compile.txt", 0 ,True
Set objReadFile = objFSO.OpenTextFile(strPath & "compile.txt",1)

Related

Keep searching for file and once it is there just open it

So, I have the following code
FileName = "Path\To\FileName"
Set FSO = CreateObject("Scripting.FileSystemObject")
Do
If FSO.FileExists(FileName) Then
FSO.DeleteFile FileName
End If
WScript.Sleep 1000
Loop
It looks for a specific file over and over again and once it is found it is deleted.
I want to modify it, I want this script to look for file over and over again and once it is found I just want to open that text file and stop the execution of the script.
Looking forward to your help :)
Use the WScript.Shell object to launch a file or application in VBScript.
FileName = "c:\tmp\newfile.txt"
Set FSO = CreateObject("Scripting.FileSystemObject")
Do
If FSO.FileExists(FileName) Then
With CreateObject("WScript.Shell")
.Run FileName ' or .Run "notepad.exe " & FileName
End With
Wscript.Quit
End If
WScript.Sleep 1000
Loop
For an HTA application, you need to use setTimeOut for the 'loop'
<script language="VBScript">
Sub CheckFile
FileName = "c:\tmp\newfile.txt"
Set FSO = CreateObject("Scripting.FileSystemObject")
If FSO.FileExists(FileName) Then
With CreateObject("Shell.Application")
.ShellExecute FileName, FileName, , , NORMAL_WINDOW ' or .ShellExecute "Notepad.exe", FileName,...
End With
Self.Close() 'exit app
End If
window.setTimeOut "CheckFile", 1000 'wait 1 second, then recheck
End Sub
CheckFile 'first check
</script>
Thanks to Hackoo for getting me on the right track :)
Just to give you an idea , I share with you an old HTA named File_Search.hta from an old forum.
<html>
<head>
<title>File Search</title>
<HTA:APPLICATION
Application ID = "SearchFiles"
APPLICATIONNAME = "File Search"
BORDER = "Dialog"
BORDERSTYLE = "Normal"
CAPTION = "Yes"
CONTEXTMENU = "Yes"
ICON = ""
INNERBORDER = "Yes"
MAXIMIZEBUTTON = "Yes"
MINIMIZEBUTTON = "Yes"
NAVIGABLE = "No"
SCROLL = "Auto"
SCROLLFLAT = "No"
SELECTION = "No"
SHOWINTASKBAR = "Yes"
SINGLEINSTANCE = "No"
SYSMENU = "Yes"
VERSION = "1.0"
WINDOWSTATE = "Normal"
/>
</head>
<style type="text/css">
a:link {color: #F19105;}
a:visited {color: #F19105;}
a:active {color: #F19105;}
a:hover {color: #FF9900;background-color: rgb(255, 255, 255);}
</style>
<script Language="VBScript">
'http://www.visualbasicscript.com/Simple-file-search-hta-m45254.aspx
Option Explicit
Dim iTimer
Sub BrowseForFolder
Dim objShell, objFolder, objFolderItem, strBrowsePath
' define constants for Shell.Application object
Const WINDOW_HANDLE = 0
Const NO_OPTIONS = 0
Set objShell = CreateObject("Shell.Application") ' Create Shell.Application object
Set objFolder = objShell.BrowseForFolder(WINDOW_HANDLE, "Choose map:",NO_OPTIONS) ' open file browser
If objFolder Is Nothing Then Exit Sub
Set objFolderItem = objFolder.Self
strBrowsePath = CStr(objFolderItem.Path) ' assign path retrieved
txtPath.value = strBrowsePath ' copy path to input box
End Sub
Sub start
Dim strInput : strInput = txtSearch.value
If strInput = "" Then
DataArea.InnerHTML = "Nothing to do."
Exit Sub ' exit sub if no keyword is specified
Else
DataArea.InnerHTML = "Busy searching..." ' update HTML body with message
iTimer = window.setInterval("Search", 1000) 'wait 1 second to ensure message is displayed
Search
End If
End Sub
Sub Search
Dim objFSO, strSearchpath, objFolderSearching, strHTML, intCount
intCount = 0
window.clearInterval(iTimer) ' clear iTimer
strSearchpath = txtPath.value ' get value from input box
Set objFSO = CreateObject("scripting.filesystemobject") ' create filesystemobject
If objFSO.FolderExists(strSearchpath) = True Then
Set objFolderSearching = objFSO.GetFolder(strSearchpath) ' get folder if it exists
Else
' give error if path is invalid and exit sub
MsgBox "Path not found. " & vbCrLf & strSearchpath,vbExclamation,"Path"
DataArea.InnerHTML = "Try again."
Set objFSO = Nothing
txtPath.Select
Exit Sub
End If
' begin building table with results
strHTML = "Results [[COUNT] File(s) Found]: <br><br>" & _
"<table border='1' style='border-collapse: collapse; font size:9pt' bordercolor='#CCCCCC' width='100%' id='Table1'>" & _
"<tr><td><strong>Name</strong></td><td><strong>Path</strong></td>" & _
"<td><strong>Size</strong></td><td><strong>Type</strong></td>" & _
"<td><strong>Modified</strong></td><td><strong>Accessed</strong></td></tr>"
CheckFolder objFolderSearching, strHTML, intCount
strHTML = strHTML & "</table>" ' call CheckFolder Function to continue building table w/ file(s) data
strHTML = Replace(strHTML, "[COUNT]", intCount)
DataArea.InnerHTML = strHTML ' display table
txtSearch.select
Set objFSO = Nothing
Set objFolderSearching = Nothing
End Sub
Sub CheckFolder(objCurrentFolder, ByRef strHTML, ByRef intCount)
Dim strSearch, objFile, strTemp, strFileName, ParentFolder, strFilePath, strFileSize
Dim strFileType, strFileModified, strFileAccess, objNewFolder
strSearch = UCase(txtSearch.value) ' get value from input box
For Each objFile In objCurrentFolder.Files ' get files in folder
On Error Resume Next
strTemp = UCase(CStr(objFile.Name))
If InStr(1, strTemp, strSearch, 1) <> 0 Then ' if file name matches keyword then build table
'Got one
intCount = intCount + 1
strFileName = objFile.Name
ParentFolder = objFile.ParentFolder
strFilePath = objFile.Path
strFileSize = FormatNumber((objFile.Size/1024),2) + " Kb"
strFileType = objFile.Type
strFileModified = objFile.DateLastModified
strFileAccess = objFile.DateLastAccessed
'"<a href=""#"" OnClick='Explore("""& Explore(strFilePath) & """)'>"& objProcess.Name &"</a>"
strHTML = strHTML & "<tr><a href=""#"" OnClick='Explore("""& strFilePath & """)'><td>" & strFileName & "</a></td><td>" &_
"<a href=""#"" OnClick='Explore("""& ParentFolder & """)'>" & _
ParentFolder & "</a></td><td>" & strFileSize & "</td>" & _
"<td>" & strFileType & "</td><td>" & strFileModified & "</td>" & _
"<td>" & strFileAccess & "</td></tr>"
End If
On Error GoTo 0
Next
For Each objNewFolder In objCurrentFolder.subFolders ' get subfolders for recursion
On Error Resume Next
CheckFolder objNewFolder, strHTML, intCount
On Error GoTo 0
Next
End Sub
Sub StartOnEnter
If window.event.keyCode = 13 Then ' if the Enter key is pressed, then call the Start sub
Start
End If
End Sub
Function Explore(filename)
Dim ws,Result
set ws = CreateObject("wscript.shell")
Result = ws.run("Explorer /n,/select,"& filename &"")
Explore = Result
End Function
</script>
<body onKeyPress="StartOnEnter" STYLE="overflow:auto;font:arial; color:#000000; filter:progid:DXImageTransform.Microsoft.Gradient (GradientType=0, StartColorStr='#FFFFFF', EndColorStr='#CCCCCC')">
<basefont SIZE="2">
Search for:<BR>
<input type="text" style="background-color:#ffffff" size="40" name="txtSearch" value="">
in&nbsp
<input type="text" style="background-color:#ffffff" size="25" name="txtPath" value="C:\">
<input id=runbutton class="button" type="button" value=" ... " name="brows_button" onClick="BrowseForFolder"><p>
<input id=runbutton STYLE="filter:progid:DXImageTransform.Microsoft.Gradient (GradientType=1, StartColorStr='#0575F1', EndColorStr='#A4C8EF')" class="button" type="button" value=" Search " name="run_button" onClick="Start"><p>
<span id="DataArea"></span>
</basefont>
</body>
</html>

Windows batch script spawn normal windows copy process

Im writing a batch script to help me collect some bandwidth data about numerous offices on our WAN. It uses random data file creator to help me avoid wan optimisers affecting the results.
How can I copy a file by spawning a standard windows copy window that shows transfer rate?
If i use the 'copy' method, it just copies silently in the cmd window and i cant see the rate.
if not exist "C:\temp\xfertest" mkdir C:\test\xfertest
rdfc C:\test\xfertest\random100.dat 100000000
copy C:\test\xfertest\random100.dat \\nat-srv-007\Deliver
exit
This vbscript wrappped in a batch file will do what you want. Save it with a .bat/.cmd extension. Or without the first line with a .vbs extension.
The technic used is based on com and works with every script language supporting it.
Just to see start/end date time, total bytes and bytes per/s it outputs these values to the console after the copy dialog window has vanished.
rem^ &#cscript //nologo //e:vbscript "%~f0" %* & exit /b
' Copy with the windows dialog box
Option Explicit
Dim cArgs : Set cArgs = WScript.Arguments
Dim iArgCnt : iArgCnt = cArgs.Count
Dim sSource : sSource = cArgs.Item(0)
Dim sDest : sDest = cArgs.Item(1)
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim oSH : Set oSH = CreateObject("shell.application")
Dim oFile, Size, dStart, dEnd
If iArgCnt <> 2 Then
Wscript.Echo "Wrong args, need SourceFile and DestFolder"
Wscript.Quit
End if
If oFS.FileExists(sSource) Then
Set oFile = oFS.GetFile(sSource)
Size = oFile.Size
If oFS.FolderExists(sDest) Then
dStart = Now()
Wscript.Echo "Copy : " & sSource & " " & sDest
Wscript.Echo "Start: " & dStart & " Size : " & Size
FolderCopyHere sSource, sDest
dEnd = Now()
Wscript.Echo "End : " & dEnd & " per/s: " & _
Int(Size / DateDiff("s", dStart, dEnd))
Else
Wscript.Echo "Destination Folder doesn't exist" & sDest
End if
Else
Wscript.Echo "Source file doesn't exist" & sSource
End if
Wscript.Quit
function FolderCopyHere(sSource,sDest)
dim oFld
set oFld = oSH.NameSpace(sDest)
if not oFld is nothing then
oFld.CopyHere(sSource)
end if
set oFld = nothing
end function
Returning this output on my pc
20:28:24 C:\Test________________________________________
> k:\Bat\CopyExpl.cmd c:\test\big.file Q:\Test
20:28:36 C:\Test________________________________________
> rem &
Copy : c:\test\big.file Q:\Test
Start: 2016-10-30 20:28:36 Size : 2147483648
End : 2016-10-30 20:29:10 per/s: 63161283
20:29:10 C:\Test________________________________________
The Rem stems from the wrapper the dialog box is widely known. HTH

Running a .bat through a .vbs

I am trying to make a pretty simple .vbs in Notepad that will do the following, but I am having a bit of trouble as I am a little new to scripting:
Execute a .bat if you select 'Yes', and close the window and do nothing if you select 'No'.
Display a message so you know why you're hitting 'Yes' or 'No'.
Display a window title.
Here's what I have tried to make myself so far:
x=msgbox("MESSAGE HERE",4,"WINDOW TITLE HERE")
const Hidden = 0
const WaitOnReturn = true
set WshShell = CreateObject("WScript.Shell")
WshShell.Run "%HOMEPATH%\Documents\FOLDER\FOLDER\EXAMPLE.BAT", Hidden, WaitOnReturn
WScript.Echo "Done"
It works just fine, however, even if I select 'No', it will still execute the .bat, which I do not want.
Try this code :
Option Explicit
Const Hidden = 0
Const WaitOnReturn = True
Dim Question,BatchFilePath,Message,Title,Result
Title = "Running a .bat through a .vbs"
Message = "Did you want to continue executing this script"
BatchFilePath = "%ProgramFiles%\FolderTest\Folder Name with spaces\EXAMPLE.BAT"
'We add the double quotes in this variable to bypass spaces issues in the path
BatchFilePath = DblQuote(BatchFilePath)
Question = Msgbox(Message,VbYesNo + VbQuestion,Title)
If Question = VbNo Then
MsgBox "You have chosen to quit this script !",vbExclamation,Title
WScript.Quit() ' We quit the script
Else
Result = Run(BatchFilePath,Hidden,WaitOnReturn)
End If
'*********************************************************************
Function Run(StrCmd,Console,bWaitOnReturn)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
'A value of 0 to hide the MS-DOS console
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success",VbInformation,Title
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
'A value of 1 to show the MS-DOS console
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success",VbInformation,Title
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function
'*********************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************
Try this one:
Set obj = CreateObject("WScript.shell")
Answer = MsgBox("Content Here",vbYesNo,"Title Here")
If Answer = vbYes Then
obj.Run "PATH TO BATCH FILE"
Else
WScript.Quit 0
End If

VB script: if file exists then run if not then end

I'm looking to use a script to go about disabling a file (REAgentc.exe) on Windows 7 machines and if it does not exist (i.e. on XP machines) then end. Below is what I've got so far but can anyone assist me in implementing the rest of what I'm after? My knowledge on VB script is admittedly not great but any help that can be offered forward would be greatly appreciated, thanks.
'Declare Variables
Dim strApp
Dim arrPath
Dim strPath
Dim strAppPath
' main if statement to run the script and call functions and sub's
If (CheckRegistryForValue)= True Then
'msgbox( strPath & " I am here")
WScript.Quit (0)
Else
RunCommand
WriteRegkey
WScript.Quit (0)
End If
'Sub to run the REAgent disable command
Sub RunCommand
Set objShell = CreateObject("Wscript.Shell")
strApp = "C:\Windows\System32\REAgentc.exe /disable"
arrPath = Split(strApp, "\")
For i = 0 To Ubound(arrPath) - 1
strAppPath = strAppPath & arrPath(i) & "\"
Next
objShell.CurrentDirectory = strAppPath
objShell.Run(strApp)
End Sub
'Function to check registry for value, Return check registry for value
Function CheckRegistryForValue
Set WshShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
dong = wshShell.RegRead ("HKLM\SOFTWARE\REAgent\")
If (Err.Number <> 0) Then
CheckRegistryForValue = False
Else
CheckRegistryForValue = True
End If
End Function
' sub to write registery key to flag computers that the script has run On
Sub WriteRegkey
HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set ObjRegistry = GetObject("winmgmts:{impersonationLevel = impersonate}!\\" & strComputer & "\root\default:StdRegProv")
strPath = "SOFTWARE\REAgent\Script Complete"
Return = objRegistry.CreateKey(HKEY_LOCAL_MACHINE, strPath)
End Sub
You can modify your RunCommand to detect & run;
dim FSO, objShell, strApp
set FSO = CreateObject("Scripting.FileSystemObject")
set objShell = CreateObject("Wscript.Shell")
'//get system path
strApp = FSO.GetSpecialFolder(1) & "\REAgentc.exe"
if FSO.FileExists(strApp) then
'//no need to change directory as you have the full path
objShell.Run(strApp & " /disable")
else
'//does not exist
end if

Creating a VBS file with the ability to write out to a text file

I have a VBS file that I am trying to use to determine what folders and files are in a certain directory. I believe I have the code written correctly, but whenever I try to write out the file or current directory I get a blank text document with nothing but the root directory written out. Any advice would be greatly appreciated.
Dim NewFile
Function GetFolders (strFolderPath)
Dim objCurrentFolder, colSubfolders, objFolder, files
Set objCurrentFolder = objFSO.GetFolder(strFolderPath)
Set colSubfolders = objCurrentFolder.SubFolders
For Each objFolder In colSubfolders
NewFile.WriteLine(" - " & objFolder.Path)
Set files = folder.Files
For each folderIdx In files
NewFile.WriteLine(" - "& folderIdx.Name)
Next
Call GetFolders (objFolder.Path)
Next
End Function
Dim fso, sFolder
Set fso = CreateObject("Scripting.FileSystemObject")
sFolder = Wscript.Arguments.Item(0)
If sFolder = "" Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If
Set NewFile = fso.CreateTextFile(sFolder&"\FileList.txt", True)
NewFile.WriteLine(sFolder)
Call GetFolders(sFolder)
NewFile.Close
You haven't payed sufficient attention to your variable naming. Your script is a good example of the reason why all VBScripts should start with the line:-
Option Explicit
This would highlight all the variables that haven't been declared which in turn will point out typos and inconsistencies in variable naming. Here is how I would write it:-
Option Explicit
Dim msFolder : msFolder = Wscript.Arguments.Item(0)
If msFolder = "" Then
Wscript.Echo "No Folder parameter was passed"
Wscript.Quit
End If
Dim mfso : Set mfso = CreateObject("Scripting.FileSystemObject")
Dim moTextStream : Set moTextStream = mfso.CreateTextFile(msFolder & "\FileList.txt", True)
moTextStream.WriteLine(msFolder)
WriteFolders mfso.GetFolder(msFolder)
moTextStream.Close
Sub WriteFolders(oParentFolder)
Dim oFolder
For Each oFolder In oParentFolder.SubFolders
moTextStream.WriteLine(" - " & oFolder.Path)
Dim oFile
For Each oFile In oFolder.Files
moTextStream.WriteLine(" - " & oFile.Name)
Next
WriteFolders oFolder
Next
End Sub

Resources