VBA excel : Using WScript to run bat file - windows

I am using the following VBA code to run a bat file. It was an example to run the note pad application instead of .bat file.
While running I am getting an error "Method run of object ISshShell3 failed"
Please let me know how can i use it to run the bat file from a desired directory?
My aim is to run a command on console and wait for the command to finish.
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim errorCode As Long
errorCode = wsh.Run("D:\test.bat", windowStyle, waitOnReturn)
If errorCode = 0 Then
MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
Thanks in advance

Related

returning error code to VBScript

Here is what I am trying to do:
Get a VBScript to run another VBScript.
get the second VBScript to post an error on completion, either 0 if successful or >0 if not back to the original script and then work on conditions Based on the error code returned.
Uninstall 2010 & copy office 2013
'Copy files from a network share to machine
Set FSO = CreateObject("Scripting.FileSystemObject")
WScript.Echo "Starting to uninstall Microsoft Office 2010 from the machine"
FSO.CopyFile "\\data01\Tools\WSM\Copy_2013.vbs", "C:\temp\Copy_2013.vbs"
FSO.CopyFile "\\data01\Tools\WSM\OffScrub10.vbs", "C:\Temp\OffScrub10.vbs"
FSO.CopyFile "\\data01\Tools\WSM\DeleteOffice13Package.vbs", "C:\temp\DeleteOffice13Package.vbs"
'Wait to execute rest of script where copied filed need to be in location
WScript.Sleep 5000
'Executes Office 2013 copy at the same time, do not wait to continue uninstalling office 2010
Set objShell = WScript.CreateObject("WScript.Shell")
Call objShell.Run("C:\temp\Copy_2013.vbs", 0, False)
WScript.Sleep 3000
'Run VBScript that uninstalls office 2010 (currently set to copy a non existent path for error capture test)
strRemoveOffice10 = "c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
Call objShell.Run(strRemoveOffice10, 0, True)
WScript.Echo Err.Number
If Err.Number <> 0 Then WScript.Echo " Microsoft Office 2010 could not be uninstalled. Please uninstall again manually."
If Err.Number = 0 Then WScript.Echo "Microsoft Office 2010 has uninstalled from the machine"
Set objFileSys = Nothing
WScript.Quit
OffScrub10.vbs
Dim objFileSys
Set objFileSys = CreateObject("Scripting.FileSystemObject")
objFileSys.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
On Error Resume Next
If Err.Number <> 0 WScript.Quit Err
To enable error handling you need to put On Error Resume Next before the statement that may cause an error. Then you can return a status code like this:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
WScript.Quit Err.Number
However, since you said you want a return value >0 in case of an error and Err.Number is an unsigned integer that might be interpreted as a positive or negative value depending on its actual value, something like this might be a better choice:
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
fso.GetFolder("C:\Temp\Temp1\bla").Copy "C:\WSM\Test"
If Err Then WScript.Quit 1
WScript.Quit 0 'can be omitted, because it's the default
To check the returned value in the calling script you need to capture it in a variable. When using the Call statement like you do in your first script the return value is simply discarded. VBScript does not put return values of external commands in the Err object. You may also want to make sure that your script is being run with cscript.exe to avoid messages/popups blocking execution.
strRemoveOffice10 = "cscript.exe c:\Temp\offscrub10.vbs ALL /Quiet /NoCancel"
rc = objShell.Run(strRemoveOffice10, 0, True)
If rc = 0 Then
'OK
Else
'an error occurred
End If
Yes, you can return an exit code from your second script to the first as follows...
WScript.Quit(-1)
Where -1 is your exit code of choice.
Option Explicit
If WScript.Arguments.Count = 0 Then
' If we don't have any arguments, call ourselves to retrieve
' the exit code. It will be returned by the call to the
' Run method
Dim returnCode
returnCode = WScript.CreateObject("WScript.Shell").Run ( _
Chr(34) & WScript.ScriptFullName & Chr(34) & " myArgument " _
, 0 _
, True _
)
' Note ^ the "True"
' We need to wait for the "subprocess" to end to retrieve the exit code
Call WScript.Echo(CStr( returnCode ))
Else
' We have arguments, leave current process with exit code
Call WScript.Quit( 1234 )
End If
Quick sample for testing.
There are two elements to consider:
The called subprocess uses the WScript.Quit method to return the process exit code to the caller
The caller must wait for the subprocess to end to retrieve the exit code. The Run method will return the exit code of the subprocess

vbscript syntax error saving a excel file

I have my code in vb script. result of a stored procedure is saved in an excel.I'm getting error in line saying
TITLE: ActiveX Script Task
Error Code: 0
Error Source= Microsoft VBScript compilation error
Error Description: Syntax error
Error on Line 97
-----------------this is the code pls help..
Dim oFSOExcelFile
Set oFSOExcelFile= CreateObject("Scripting.FileSystemObject")
Dim workSheet,sFileName
Dim iRow,headingRow
'Create the Excel workbook
On error Resume Next
Set oXLIDRenewal = CreateObject("Excel.Application")
oXLIDRenewal.Visible=True
With oXLIDRenewal
'Make sure there is no minimized window.
.Application.Visible = False
.Application.DisplayAlerts = False
End With
If not rstRev.EOF then
'Name of the excel File to import to.
sFileName=''D:\packages\Rev&CPExcel\Rev'' &iday &''-''&imonth ''-''&iyear &''.xls''
'Delete the Excel File if it already exists.
If oFSOExcelFile.FileExists(sFileName) Then
On Error Resume Next
oFSOExcelFile.DeleteFile(sFileName)
End If
Your
sFileName=''D:\packages\Rev&CPExcel\Rev'' &iday &''-''&imonth ''-''&iyear &''.xls''
uses the wrong quotes and lacks at least one &. So try:
sFileName = "D:\packages\Rev&CPExcel\Rev" & iday & "-" & imonth & "-" & iyear & ".xls"
Double check ..\Rev&CPExcel\..

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.

Shell.Run with arguments

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.

Why does VBScript sometimes block in WshShell.Exec?

I've got an html application (HTA) that uses WshShell.Exec to get the version of Windows. I'm using wmic os get Caption to get the specific version, which works fine on the command line and in a batch script. I've also tested the way I'm calling WshShell.Exec and it works fine with other commands (i.e. echo Windows 2008). The problem occurs when I try to combine these things the Exec seems to just freeze. Can you recommend a way around this? Here's my code:
Function GetWinVersion
'Returns 2008, XP, or 7
set WshShell = CreateObject("WScript.Shell")
set oExec = WshShell.Exec("wmic os get Caption")
do while oExec.Status = 0
'I added this very busy wait, though it doesn't seem to help
'Would sleep if it was available in an hta
loop
While oExec.StdOut.AtEndOfStream <> True
thisLine = oExec.StdOut.ReadLine
'MsgBox "Found line: " & thisLine
if InStr(thisLine, "2008") > 0 then
GetWinVersion=2008
Exit Function
elseif InStr(thisLine, "XP") > 0 then
GetWinVersion=XP
Exit Function
elseif InStr(thisLine, "Windows 7") > 0 then
GetWinVersion=7
Exit Function
end if
Wend
MsgBox "Error parsing output of wmic os get Caption"
self.Close
End Function
WMIC is a wrapper for WMI, which you can use directly in VBS;
function GetWinVersion
dim WMI: set WMI = GetObject("winmgmts:\\.\root\cimv2")
dim colResults: set colResults = WMI.ExecQuery("Select * from Win32_OperatingSystem")
dim item
for each item in colResults
GetWinVersion = item.caption
next
end function

Resources