Getting "file not found" error - vbscript

I don't understand why this code:
Set oWMP = CreateObject("WMPlayer.OCX.7")
Set oCMD = CreateObject("WScript.Shell")
Sub OpenFile(file)
oCMD.run file
End Sub
Sub OpenCMD
oCMD.run "%COMAPEC% /c start cmd"
End Sub
Sub Blink
oCMD.run "%COMAPEC% /c exit"
End Sub
Sub Wait(seconds)
oCMD.run "%COMSPEC% /c ping -n " & seconds+1 & " 127.0.0.1", 0, True
End Sub
Sub PromptCommand(command)
oCMD.run "%COMAPEC% /c " & command
End Sub
Blink
Wait("0.5")
OpenCMD
Wait("7")
OpenFile("C:\Documents and Settings\Scott\Desktop\Lemmings\LEMMINGS.bat")
gives me the following error:

With line 13 being
oCMD.run "%COMAPEC% /c exit"
I'd suspect that you simply mistyped the environment variable. Replace every occurrence of %COMAPEC% in your script with %COMSPEC%.
And, of course, always put paths between double quotes, as #Ekkehard.Horner recommended. You can simplify the handling by using a quoting function like this:
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
oCMD.Run qq(file)
which is a bit better readable than a bunch of string concatenations.

Start with quoting the command line passed to .Run:
oCMD.run """" & file & """""
instead of:
oCMD.run file
(cf. this)

Related

How do I convert the weekday command so that I can manually pick the day for each task rather than it detecting it automatically?

When I started on this I wasn't aware that I had to be able to select each daily task manually and pick each task whenever I want, I'm trying to figure out how to convert it into a manual entry so I don't have to rework the whole thing, bear in mind I'm very new to vbscript so if there's an obvious solution I apologize. I'm still working on the later days of the week to finish this.
dtmToday = Date()
dtmDayOfWeek = DatePart("w", dtmToday)
'Select case to pickup the value of day of the week and call procedure
Select Case dtmDayOfWeek
Case 1
Call Sunday()
Case 2
Call Monday()
Case 3
Call Tuesday()
Case 4
Call Wednesday()
Case 5
Call Thursday()
Case 6
Call Friday()
Case 7
Call Saturday()
End Select
'Sunday procedure will execute from select case
sub Sunday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' Execute the command and append to the text file
WShShell.run "cmd /c ping -n 10 youtube.com >> ping.txt", hidden
wscript.quit
End sub
'Monday procedure will execute from select case
sub Monday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' to execute the command and append to the text file using >> if you want to text to be overriden use >
WShShell.run "cmd /c netstat >> netstat.txt", hidden
wscript.quit
End sub
'Tuesday procedure will execute from select case
sub Tuesday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' to execute the command and append to the text file using >> if you want to text to be overriden use >
WShShell.run "cmd /c arp -a >> arp.txt", hidden
wscript.quit
End sub
sub Wednesday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
WShShell.run "cmd /c nbstat -n >> nbstat.txt", hidden
wscript.quit
End Sub
sub Thursday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
WShShell.run "cmd /c tracert -n 10 youtube.com >> nbstat.txt", hidden
wscript.quit
End Sub
You need first optimize your code to avoid heavy duplication as #Lankymart was mentioned it in his comment, by writing one function and call it when you need it, and to store all your commands into an array for easy access by their index.
So your code can be written like that :
Option Explicit
' We define our Global variables
Dim Title,ArrCommands,strcmd,dtmDayOfWeek,IndexCommand,UserInput
Title = "Run command line based on the Day Of Week"
'----------------------------------------------------------------------------------
' We define and store our commands lines into an array
ArrCommands = Array(_
"ping -n 10 youtube.com >> ping.txt",_
"netstat >> netstat.txt",_
"arp -a >> arp.txt",_
"Color 0A & Title Running nbtstat command & nbtstat -n",_
"Color 0A & Title Running Tracert command & tracert youtube.com",_
"Color 0A & Title Running Ipconfig command & Ipconfig /all",_
"Color 0A & Title Running netstat command & netstat -ano"_
)
'-------------------------------Main Program---------------------------------------
Do While Not IsDate(UserInput)
UserInput = InputBox("Type a date here example 24/06/2020",Title,"24/06/2020")
dtmDayOfWeek = MyWeekday(UserInput)
IndexCommand = dtmDayOfWeek - 1
Loop
MsgBox "Day of the Week = "& dtmDayOfWeek & vbCrlf &_
"The command will be executed is : "& ArrCommands(IndexCommand),vbInformation,Title
'Select case to pickup the value of day of the week
Select Case dtmDayOfWeek
Case 1
Call Execute(ArrCommands(IndexCommand),0)
Case 2
Call Execute(ArrCommands(IndexCommand),0)
Case 3
Call Execute(ArrCommands(IndexCommand),0)
Case 4
Call Execute(ArrCommands(IndexCommand),1)
Case 5
Call Execute(ArrCommands(IndexCommand),1)
Case 6
Call Execute(ArrCommands(IndexCommand),1)
Case 7
Call Execute(ArrCommands(IndexCommand),1)
End Select
'MsgBox "Command line is done",vbInformation,Title
'----------------------------------------------------------------------------------
Function MyWeekday(MyDate)
If MyDate = "" Then MyDate = Date()
If IsDate(MyDate) Then
MyWeekDay = Weekday(MyDate)
Exit Function
End If
End Function
'----------------------------------------------------------------------------------
Sub Execute(StrCmd,Console)
Dim ws,MyCmd
Set ws = CreateObject("wscript.Shell")
'The console = 0 means will be running in hidden mode
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & " "
ws.run MyCmd,Console,True
End If
'The console = 1 means will be running in not hidden mode
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & " "
ws.run MyCmd,Console,True
End If
End Sub
'----------------------------------------------------------------------------------

findstr() Runtime error 23 when called as a subprocess?

I am attempting to run findstr command from within my vb6 project however it seems that I am in over my head in determining the correct syntax.
I was calling a batch file to run the findstr but trying to integrate it in the project is failing.
'''''''' Lines below allow ONLY Numeric text in teh Test1 box
Dim textval As String
Dim numval As String
Private Sub Text1_Change()
textval = Text1.Text
If IsNumeric(textval) Then
numval = textval
Else
Text1.Text = CStr(numval)
End If
End Sub
'''''''' Lines above allow ONLY Numeric text in teh Test1 box
Private Sub Command1_Click()
''''Lines below enables program/project to execute in the current `enter code here`directory
Dim MyCurrentDir As String
'Show current directory
MyCurrentDir = CurDir
' MsgBox "Current Directory is " & MyCurrentDir
''''Lines above enables program/project to execute in the current directory
' Remarked for testing below WORKS: Shell (MyCurrentDir & "\findstring.bat " & Text1)
' TEST BELOW
Dim command As String
'findstr "%1" *achineCont*.log | findstr "Q_OUTFEED_EJECTBAG_SIG">FOUNDBAG.txt
command = "findstr "" & Text1 & "" *achineCont*.log | findstr ""Q_OUTFEED_EJECTBAG_SIG"">FOUNDBAG.txt"
Shell "cmd.exe /c command"
'findstr "Done" *ai*.log | findstr "writing" | findstr "%1">>FOUNDBAG.txt
Command2 = "Done"" *ai*.log | findstr ""writing"" | findstr "" & Text1 & "">>FOUNDBAG.txt"
Shell "cmd.exe /c command2"
'start "" cmd /c cscript ReadTimeFromFileWriteToNewFile.vbs
Command3 = "start """" cmd /c cscript ReadNewFile.vbs"
Shell "cmd.exe /c command3"
' TEST ABOVE
End Sub
Private Sub Command2_Click()
Unload Form1 'tell the form to unload
Set Form1 = Nothing 'free the memory used by the variables
End Sub
Private Sub Form_Load()
''''Lines below enables program/project to execute in the current directory
Dim MyCurrentDir As String
'Show current directory
MyCurrentDir = CurDir
' MsgBox "Current Directory is " & MyCurrentDir
''''Lines above enables program/project to execute in the current directory
End Sub
You are several quotes away from being correct in each command. You need to triple up some of the quotes, and re-position some of the others. For the first command, try this:
Command = "findstr """ & Text1 & """ *achineCont*.log | findstr ""Q_OUTFEED_EJECTBAG_SIG"">FOUNDBAG.txt"
For the second command, try this:
Command2 = """Done"" *ai*.log | findstr ""writing"" | findstr """ & Text1 & """>>FOUNDBAG.txt"
And last but not least, for the fourth command, try this:
Command4 = "findstr ""Done"" *ai*.log | findstr ""writing"" | findstr """ & Text1 & """>>FOUNDBAG.txt"
A good way to figure these out is to display the string with either Debug.Print or a MsgBox and adjust quotes until the string is correct. Also, remember a string has opening and closing quotes. Any other quotes within the string need to be escaped by doubling up the quote.

Run Rscript.exe with VBScript and spaces in path

I have the followaing run.vbs script
Rexe = "R-Portable\App\R-Portable\bin\Rscript.exe"
Ropts = "--no-save --no-environ --no-init-file --no-restore --no-Rconsole "
RScriptFile = "runShinyApp.R"
Outfile = "ShinyApp.log"
startChrome = "GoogleChromePortable\App\Chrome-bin\chrome.exe --app=http://127.0.0.1:9999"
strCommand = Rexe & " " & Ropts & " " & RScriptFile & " 1> " & Outfile & " 2>&1"
intWindowStyle = 0 ' Hide the window and activate another window.'
bWaitOnReturn = False ' continue running script after launching R '
' the following is a Sub call, so no parentheses around arguments'
CreateObject("Wscript.Shell").Run strCommand, intWindowStyle, bWaitOnReturn
WScript.Sleep 1000
CreateObject("Wscript.Shell").Run startChrome, intWindowStyle, bWaitOnReturn
It works pretty well in most cases except when the user puts the run.vbs script in a folder with spaces in its name: e.g. if run.vbs is in folder "foo bar", the user gets the error : "C:\Users\[user name]\Desktop\foo" not recognized as internal command...
I don't understand why Rscript.exe looks for the absolute path before running even if it's called from its parent directory using relative path.
I heard about the double quote solution using the absolute path but it doesn't seem to work with .exe scripts (it does though with .bat and .cmd)
Thanks for any help!
Below code will help you
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec("C:\Program Files\R\R-3.2.3\bin\Rscript.exe C:\subfolder\YourScript.R " & """" & var1 & """")
Set oOutput = oExec.StdOut
handle the results as they are written to and read from the StdOut object
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend

How can I execute a command from command line in back ground

I have written vb script to run jar command from windows command line in foreground
'File paths
processFile = "java -jar doSomething.jar C:\folder1\subFolder1 C:\folder2\subFolder2"
Set objShell = CreateObject("Wscript.shell")
objShell .run "cmd /k CD C:\VBScriptfolder\script" 'Path to vbscript which contains command to run from command line
WScript.Sleep 5000
Wait(5)
objShell .SendKeys processFile
WScript.Sleep 3000
Wait(3)
objShell .SendKeys "{ENTER}"
WScript.Sleep 40000
Wait(60)
objShell .SendKeys "exit{ENTER}"
But my question is that how to run above command from command line which execute the command in background instead of foreground.
Try to build your command line and debug it with wscript.echo.
And, if you feel that it is correct , you should comment the wscript.echo and uncomment this line Call Run(StrCmd,0,False) 'Hiding the console
Option Explicit
Dim StrCmd,Path,processFile
Path = "C:\VBScriptfolder\script" 'Path to vbscript which contains command to run from command line
processFile = "java -jar doSomething.jar C:\folder1\subFolder1 C:\folder2\subFolder2"
StrCmd = "CD /D "& Path & " & " & processFile &""
wscript.echo StrCmd
'Call Run(StrCmd,1,False) 'Showing the console
'Call Run(StrCmd,0,False) 'Hiding the console
'**********************************************************************************************
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"
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"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function
'**********************************************************************************************

VBscript Robocopy Syntax

I am having a problem with what I think is a syntax error in VBscript regarding running robocopy.
The following is a code snippet of what I now using to try to run robocopy:
Dim Command2
sLocalDestinationPath = "C:\Script\files\outzips\"
sFinalDestinationPath = "C:\CopyTestFolder\"
Command2 = "Robocopy.exe " & sLocalDestinationPath & " " & sFinalDestinationPath
The thing is that the command does not produce any errors, but it also does not copy any files from the local path to the final path. It runs perfectly fine when executed from the command line. Any help would be greatly appreciated because this simple command is keeping me from finishing the rest of this script.
I also have it echoing out the command and the command matches exactly what I put in the command line.
Thank you, if you need anymore explanation just let me know.
You don't say how you are trying to 'run' Robocopy, but I presume it is via WScript.Shell.Run().
I don't happen to have Robocopy handy, but I did work up an example using Windows XCopy. Perhaps you can adapt my simple XCopy example to gain more insight into your problem with Robocopy.
Option Explicit
' XCOPY doesn't Like trailing slashes in folder names
Const sLocalDestinationPath = "C:\Script\files\outzips"
Const sFinalDestinationPath = "C:\CopyTestFolder"
Dim Command2 : Command2 = _
"XCOPY" _
& " " & sLocalDestinationPath _
& " " & sFinalDestinationPath _
& " /E /I /Y" _
& ""
Dim oSh : Set oSh = CreateObject("WScript.Shell")
WScript.Echo "Cmd: [" & Command2 & "]"
On Error Resume Next
Dim nRetVal : nRetval = oSh.Run(Command2, 0, True)
If Err Then
WScript.Echo "An exception occurred:" _
& vbNewLine & "Number: [" & Hex(Err.Number) & "]" _
& vbNewLine & "Description: [" & Err.Description & "]" _
& ""
Else
If nRetVal Then
WScript.Echo "Copy error: [" & nRetVal & "]"
Else
WScript.Echo "Copy succeeded."
End If
End If
Set oSh = Nothing
' XCOPY options:
'
' /E Copies directories and subdirectories, including empty ones.
' Same as /S /E. May be used to modify /T.
'
' /I If destination does not exist and copying more than one file,
' assumes that destination must be a directory.
'
' /Y Suppresses prompting to confirm you want to overwrite an
' existing destination file.
' End

Resources