Shell.Run with arguments - vbscript

I'm trying to run a program (with argument /config) using Shell.Run from VBS. However I'm having an exit code = 87 (cannot find the file specified).
1st piece of code I've tried:
strCommand = """c:\Program Files\Test\launch.exe""" & " /config:C:\sample.xml"
intExit = objShell.Run(strCommand, 0, True)
2nd piece of code:
Dim FileExe, Argum
FileExe = "%ProgramFiles%\Test\launch.exe"
Argum = "/config:C:\sample.xml"
RunMe FileExe, Argum
Function RunMe(FileExe, Argum)
Dim Titre, ws, Command, Exec
Titre = "Execution avec argument"
Set ws = CreateObject("WScript.Shell")
command = "cmd /c "& qq(FileExe) & " " & Argum &" "
Msgbox command, 64, Titre
Exec = ws.Run(command, 0, True)
End Function
Function qq(str)
qq = chr(34)& str &chr(34)
End Function

Of course yes, the Run command is supposed to return something.
I was here because I was hesitant about the second parameter. I found it there :
Documentation of Windows Script Host Run method, on vbsedit.com
Shell.Run returns the return value of the command line that it executes, so in this case, you will find the signification of the return code in the documentation of the Launch program, in the Test folder. (Test means what it means ...)
Of course it would ease the comprehension if the Launch program respected the conventions about the significations of the codes, but for a test you do not always enter into those details. Probably because of this, 87 remains me nothing. A missing file is a quite classical error, with code 2. But perhaps 2 would be for a data file.

Related

Use VBS to run a program with parameters

I'm a total vbs novice trying to perform the supposedly simple task of using a vbscript to run a single program (with parameters).
The path the to program is:
C:\Program Files (x86)\SpeedyFox\speedyfox.exe
and the parameter switch that must go with it is:
/Firefox:C:\Program Files\Firefox\Data\profile
If I wrap both sections in quotes (due to the spaces in their paths) it gives the following combined single command:
"C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile"
If I then paste this into Start > Run it works exactly as I want.
I'm just trying to achieve the same thing from a vbs script instead of manually pasting into the Run box.
I do not want the command to run within a CMD console (as other questions on here have asked). All I am trying to do is to get "C:\Program Files (x86)\SpeedyFox\speedyfox.exe" "/Firefox:C:\Program Files\Firefox\Data\profile" to work with the shell.ShellExecute line of the script below.
Set objShell = Wscript.CreateObject ("Wscript.shell")
set shell=CreateObject("Shell.Application")
shell.ShellExecute ** WHAT DO I PUT HERE? **
set shell=nothing
but try as I might, I just keep getting WSH "Expected end of statement" error messages.
1.First : I recommend you Make it a habit to use this quote function
to make it easy for you to quote variables in these situations !
2. Second : You should use MsgBox or Wscript.echo in order to show
and debug your variables easily !
Wscript.echo DblQuote("Hello World !")
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
So, I downloaded this application (speedyfox.exe) and i tested it on my Windows 10 (32bits)
So, here is what i tested and it works like a charm on my side :
Option Explicit
Dim objShell,MyCommand,strProgramFiles,SpeedyFoxfile,Title
Title = "Execute SpeedyFox in Commandline"
Set objShell = CreateObject("Shell.Application")
strProgramFiles = GetProgramFilesPath()
SpeedyFoxfile = strProgramFiles & "\SpeedyFox\speedyfox.exe"
MsgBox "Without Double Quotes" & vbCrlf & SpeedyFoxfile,vbInformation,Title
MsgBox "With Double Quotes" & vbCrlf & DblQuote(SpeedyFoxfile),vbInformation,Title
MyCommand = "CD /D "& DblQuote(strProgramFiles &"\SpeedyFox\") &"&"& DblQuote(SpeedyFoxfile) & " " & DblQuote("/Firefox:default") & " " & DblQuote("/Chrome:Default")
MsgBox MyCommand,vbInformation,Title
Call Execute(MyCommand)
'-----------------------------------------
Function Execute(StrCmd)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
MyCmd = "CMD /K " & StrCmd & ""'
Result = ws.run(MyCmd,1,True)
Execute = Result
End Function
'-----------------------------------------
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'-----------------------------------------
Function GetProgramFilesPath()
Dim ws,OsType,strProgramFiles
Set ws = createObject("WScript.Shell")
OsType = ws.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\PROCESSOR_ARCHITECTURE")
If OsType = "x86" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES%")
elseif OsType = "AMD64" then
strProgramFiles = ws.ExpandEnvironmentStrings("%PROGRAMFILES(x86)%")
end if
GetProgramFilesPath = strProgramFiles
End Function
'-----------------------------------------
Sigh, reminds me of my vbscript days, now I use Ruby and it's just as simple as
´my_shell_command params´
However, back to your question: the shortest way to use ShellExecute is
CreateObject("Shell.Application").ShellExecute "application", "parameters", "dir", "verb", window
See this documentation for explanation of the parameters.
EDIT:
You have to pay attention at the quotes, they need to be passed to the shell also by using two quotes
eg CreateObject("Shell.Application").ShellExecute "C:\Program Files (x86)\SpeedyFox\speedyfox.exe", """/Waterfox:C:\Program Files\Waterfox\Data\profile"""

VBScript's Shell Command Will Not Execute Unless An Output File Is Specified

I'm trying to run a shell command for google speech recognition. I'm able to run the command only if I provide an output file to the command string.
As you can see my test code sample below, I would attach the ">outputFile" if one is provided and also coded in a timeout loop to abort the process after a set time limit.
strCommand = "cmd /c ipconfig /all"
If outputFile <> "" Then
strCommand = strCommand & " > """ & outputFile & """"
End If
Set wshShellExec = wshShell.Exec(strCommand)
expiration = DateAdd("s", 600, Now)
Do While wshShellExec.Status = WshRunning And Now < expiration
WScript.Sleep 5000
Loop
Select Case wshShellExec.Status
Case WshRunning
wshShellExec.Terminate
TestFunction = "{""error"": ""TestFunction Command Timed Out""}"
Case WshFinished
TestFunction = WshShellExec.StdOut.ReadAll()
Case WshFailed
TestFunction = wshShellExec.StdErr.ReadAll()
End Select
If I leave outputFile empty and try to expect the output to be returned from the function, all it does is sit still for 5 minutes before timing out and sending me my error message.
Why does it need an output file to run?
If I run the command line manually on a Command Prompt, it runs perfectly fine.
Output buffers have limited capacity. If your command writes too much text to stdout the buffer will fill up and block the command from writing more until you clear the buffer (e.g. by reading from it). ReadAll can't be used for that, though, because that method will only return after the command has finished and block otherwise, thus creating a deadlock.
Your best option is to redirect output to one or more (temp) files, and read the output from those files after the command has finished.
outfile = "C:\out.txt"
errfile = "C:\err.txt"
cmd = "cmd /c ipconfig /all >""" & outfile & """ 2>""" & errfile & """"
timeout = DateAdd("s", 600, Now)
Set sh = CreateObject("WScript.Shell")
Set ex = sh.Exec(cmd)
Do While ex.Status = WshRunning And Now < timeout
WScript.Sleep 200
Loop
Set fso = CreateObject("Scripting.FileSystemObject")
outtxt = fso.OpenTextFile(outfile).ReadAll
errtxt = fso.OpenTextFile(errfile).ReadAll
If you don't want to do that for some reason you must read from StdOut repeatedly.
outtxt = ""
errtxt = ""
cmd = "ipconfig /all"
timeout = DateAdd("s", 600, Now)
Set sh = CreateObject("WScript.Shell")
Set ex = sh.Exec(cmd)
Do While ex.Status = WshRunning And Now < timeout
WScript.Sleep 200
outtxt = outtxt & ex.StdOut.ReadLine & vbNewLine
Loop
Note that you may also need to read from StdErr, because that buffer might fill up too if there is too much error output. However, reading both buffers might create another deadlock, because IIRC ReadLine blocks until it can read a full line, so if the script might hang waiting for error output that never appears. You might be able to work around that by using Read instead of ReadLine, but it'll still be very fragile.
So, again, your best option is to redirect command output to files and read those files after the command terminates.
Once the wshShellExec is terminated in the WshRunning case, instead of assigning the error message, the output should be assigned.
Select Case wshShellExec.Status
Case WshRunning
wshShellExec.Terminate
TestFunction = "Terminated: " & vbcrlf & WshShellExec.StdOut.ReadAll()
Case WshFinished
TestFunction = "Finished: " & vbcrlf & WshShellExec.StdOut.ReadAll()
Case WshFailed
TestFunction = wshShellExec.StdErr.ReadAll()
End Select

MSAccess VBA Shell Command - Max Length?

I've been tearing my hair out this afternoon. From Access VBA I've been issuing a Command line via a shell to FTP a file to a 3rd party server using cURL.exe.
Things were working great until I brought my code to production where it is now failing silently. I suspect the multiple unpredictable file paths producing "strCmd" are just too long to pass thru the Command shell. >> Is there a limit? <<
fShellRun (strCmd)
curl -k -T testfile.txt --ftp-ssl --ftp-pasv -u "username\$domain:password" ftp://ftp-domain.egnyte.com/Shared/testdirectory/
This is the Shell function I am using (not mine):
Function fShellRun(sCommandStringToExecute)
Dim oShellObject, oFileSystemObject, sShellRndTmpFile
Dim oShellOutputFileToRead, iErr
Set oShellObject = CreateObject("Wscript.Shell")
Set oFileSystemObject = CreateObject("Scripting.FileSystemObject")
sShellRndTmpFile = oShellObject.ExpandEnvironmentStrings("%temp%") & oFileSystemObject.GetTempName
On Error Resume Next
oShellObject.Run sCommandStringToExecute & " > " & sShellRndTmpFile, 0, True
iErr = Err.Number
'~on error goto 0
If iErr <> 0 Then
fShellRun = ""
Exit Function
End If
'~on error goto err_skip
fShellRun = oFileSystemObject.OpenTextFile(sShellRndTmpFile, 1).ReadAll
oFileSystemObject.DeleteFile sShellRndTmpFile, True
Exit Function
err_skip:
fShellRun = ""
oFileSystemObject.DeleteFile sShellRndTmpFile, True
End Function
I am noticing strCmd longer than ~200 chars fails silently.
Questions:
Is there a string length limit using a command shell?
How might I circumvent this limit?
Thanks!
Edit: The long command string (copy/paste from debug.print) works just fine in an open command window. Leads me to think there is an issue with the shell command itself. (?)

Writing an output of shellExecute command with arguments into a log file in VBScript

I've tried a lot of things to accomplish this, but haven't succeeded yet in the way I'd like to.
I've got an hta app, that gathers parameters from checkboxes and then runs a cmd file passing those parameters there.
I want to create a log file of that process without creating any new wrapping files if a log checkbox is checked.
My logic is to run a script with arguments by another with redirecting parameter as an argument. And I can't get the syntax right (or is it even possible inside the same file). My simplified code:
Sub RunCmd
dim shell
dim shellWithLog
dim command
dim ARGS
set shell = createobject("Shell.Application")
set shellWithLog = createobject("wscript.shell")
command = "gui.cmd"
if (checkbox1.checked) then
ARGS = ARGS + " Do_This"
end if
if (checkbox2.checked) then
ARGS = ARGS + " Do_That"
end if
if (logFile.checked) then
shellWithLog.run (shell.shellExecute command, ARGS), " &>" + "publishLog.log", 1
else
shell.shellExecute command, , "runas", 1
end if
End Sub
This doesn't work, obviously, but at least shows what I'm trying to achieve.
To concatenate strings in VBScript, the & operator is used. The + operator is for numerical addition only.
Sub RunCmd
dim shell, ARGS
set shell = createobject("Shell.Application")
ARGS = ""
if checkbox1.checked then ARGS = ARGS & " Do_This"
if checkbox2.checked then ARGS = ARGS & " Do_That"
if logFile.checked then ARGS = ARGS & ARGS " > publishLog.log"
' ShellExecute(sFile, [vArgs], [vDirectory], [vOperation], [vShow])
' https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx
shell.shellExecute "gui.cmd", ARGS, , "runas", 1
End Sub

Run script in background

I want to run following script as scheduled task on Windows 7 in background. Now, script displays cmd window and, can I run script without visible cmd window?
Option Explicit
Dim WshShell, oExec
Dim RegexParse
Dim hasError : hasError = 0
Set WshShell = WScript.CreateObject("WScript.Shell")
Set RegexParse = New RegExp
Set oExec = WshShell.Exec("%comspec% /c echo list volume | diskpart.exe")
RegexParse.Pattern = "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*"
While Not oExec.StdOut.AtEndOfStream
Dim regexMatches
Dim Volume, Drive, Description, Redundancy, RaidStatus
Dim CurrentLine : CurrentLine = oExec.StdOut.ReadLine
Set regexMatches = RegexParse.Execute(CurrentLine)
If (regexMatches.Count > 0) Then
Dim match
Set match = regexMatches(0)
If match.SubMatches.Count >= 8 Then
Volume = match.SubMatches(0)
Drive = match.SubMatches(1)
Description = Trim(match.SubMatches(2))
Redundancy = match.SubMatches(4)
RaidStatus = Trim(match.SubMatches(7))
End If
If RaidStatus <> "Healthy" Then
hasError = 1
'WScript.StdOut.Write "WARNING "
MsgBox "Status of " & Redundancy & " " & Drive & ": (" & Description & ") is """ & RaidStatus & """", 16, "RAID error"
End If
End If
Wend
WScript.Quit(hasError)
Thanks a lot
Option 1 - If the task is running under your user credentials (if not, msgbox will not be visible)
There are two possible sources for the cmd window.
a) The script itself. If the task is executing cscript, the console window will be visible, avoid it calling wscript instead
b) The Shell.exec call. The only way to hide this window is to start the calling script hidden. On start of your script test for the presence of certain argument. If not present, make the script call itself with the argument, using Run method of the WshShell object, and indicating to run the script with hidden window. Second instance of the script will start with the special parameter, so it will run, but this time windows will be hidden.
Option 2 - Running the task under system credentials.
In this case, no window will be visible. All will be running in a separate session. BUT msgbox will not be seen. Change MsgBox call with a call to msg.exe and send a message to current console user.

Resources