wscript exec cmd.exe /c does not report error - windows

I try several version of Wscript exec method.
If i use a cmd.exe /C MyRequest, the execution does not report an error if the MyRequest is failing but return the error if cmd.exe /c is not used.
I was thinking that cmd.exe is reporting the return code of the call to the MPyRequest but seems not. How to retreive the return code in this case.
Here is the simplified version of my test (comment direct version to have the non failure)
Environnement will be mainly windows 7 (normaly no other system, maybe XP)
' Missing.cmd does not exist to force the failure test
'version with cmd.exe (CmdDir content is a valid and working cmd.exe)
ExecCmd = CmdDir & " /c Missing.cmd 1"
' direct version
ExecCmd = "Missing.cmd 1"
Set objShell = CreateObject("WScript.Shell")
On Error Resume Next
Set oExec = objShell.exec( ExecCmd)
' -- Post treatment ---------------------------
If ( err.Number = 0) Then
If ( oExec.ExitCode = 0 ) Then
' No error
wscript.echo "Execution OK"
Else ' Exit with error
wscript.echo "Error :" & oExec.ExitCode
end if
Else ' error on exec itself
wscript.echo "Execution. Error on object at call: " & err.Number _
& " Source: " & Err.Source & " Desc: " & Err.Description
end if
Solution based on all your reply (thanks all) [ #Damien, #Ekkehard.Horner, #Hans Passant]
check error (via on error and err.Number) for vbs internal error like bad variable/method call. This should be at exec call sub level (so not at main process if exec call is in a function/subroutine)
exec.status to wait until it change to 1. Wait is a following process checking the status, not like a shell.sleep
during this wait, catch stdout/stderr with a AtEndOfStream if life info is needed (if not, read after the close of the process)
for a timeout process, use a cycle of shell.sleep with an exit (of cycle) if timeout or other event is trapped (I use a counter associate to a clock time/sleep time in this case) and exit the loop if trigger occur associate with a exec.Terminate to kill the process in this case (depending of your need ...)

You need to check the ExitCode property.

If it is actually returning an error code, perhaps you are processing exitcode to early. Maybe add in oexec.StdOut.ReadAll() to make it wait until completion.
Perhaps you could add in something like this
....
....
Set oExec = objShell.exec(ExecCmd)
oExecResult = oexec.StdOut.ReadAll()
SessionExitCode = oexec.ExitCode
' -- Post treatment ---------------------------
If ( err.Number = 0) Then
If ( SessionExitCode = 0 ) Then
' No error
wscript.echo "Execution OK"
Else ' Exit with error
wscript.echo "Error :" & SessionExitCode
end if
Else ' error on exec itself
....
....

Related

Pre-load a program in VBScript for more efficient execution

I have a VBS script (compiled to an .exe, actually) that invokes another program (.exe) using the VBS Run instruction. My mainframe mentality tells me that it would be beneficial to pre-load this second program at the start of my script, so that it is available immediately when needed further down the line. Typically on mainframe, when appropriate, one would LOAD the program into memory at some point and then branch to it later.
Does this concept exist in VBS?
Thanks for any advice.
It is easy to start a program in a suspended state, but I have still not found a way to later resume the execution without a external tool (we need to call ResumeThread API). For this sample I have used the Windows SysInternal's PsSuspend tool to resume the process.
Option Explicit
Const SW_NORMAL = 1
Const CF_CREATE_SUSPENDED = 4
Const PROCESS_NAME = "Notepad.exe"
' Instantiate required objects
Dim wmi, shell
Set wmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set shell = WScript.CreateObject("WScript.Shell")
' Prepare the startup configuration for the process
' https://msdn.microsoft.com/en-us/library/aa394375%28v=vs.85%29.aspx
Dim startUp
Set startUp = wmi.Get("Win32_ProcessStartup").SpawnInstance_
With startUp
.ShowWindow = SW_NORMAL
.CreateFlags = CF_CREATE_SUSPENDED
End With
' Start the process
' https://msdn.microsoft.com/en-us/library/aa394372%28v=vs.85%29.aspx
Dim retCode, processID
retCode = wmi.Get("Win32_Process").Create( PROCESS_NAME, Null, startUp, processID )
If retCode <> 0 Then
Wscript.Echo "Process creation failed: " & retCode
WScript.Quit 1
End If
WScript.Echo "Process created with PID: " & processID
' Ask the OS to check for presence of our process
WScript.Echo shell.Exec("tasklist /fo:list /v /fi ""imagename eq " & PROCESS_NAME & """").StdOut.ReadAll()
' Wait (not required, just for testing)
WScript.Sleep 5000
' Resume the process - SysInternals pssuspend required
' https://technet.microsoft.com/en-us/sysinternals/pssuspend.aspx
Call shell.Run("pssuspend64.exe /accepteula -r " & processID, 0, False)
' Wait for the process to resume and show again the task list
WScript.Sleep 2000
WScript.Echo shell.Exec("tasklist /fo:list /v /fi ""imagename eq " & PROCESS_NAME & """").StdOut.ReadAll()

VBScript Error "Permission Denied" But Works Anyway

I have a VBScript setup as a logon script in my GPO. I'm having an issue where every time it runs at logon, I get Permission Denied on the line:
set lf = fso.opentextfile(lfp, 2, true)
Points of interest:
Despite the error, the script completes successfully.
The script executes without error if I run it manually.
The lfp variable points to c:\folder\folder\file.log. The file is created (when necessary) and populated appropriately (overwritten, as expected when it does exist).
If the file is created, the fso is closed before trying to opentextfile.
The user logging in does have modify permission to the path and to the file being replaced when it exists via inherited Authenticated Users permission (from c:\folder1 - see below).
If I throw in a wscript.sleep 30000 just before that line, it just waits 30 seconds to throw permissions denied.
If user is a member of local administrators group on PC, I get no errors. Again, when user is not local admin, it errors, but completes successfully.
I see the same behavior under both Windows 7 and 10.
I'm at a loss here. Here's the pertinent section of code (please excuse any poor coding practice):
'notify robocopy log file location
function seelog(log)
lf.writeline "[" & now & "] " & "See log file for details: " & log
end function
'process robocopy exit codes and write log
function writeerrors(items)
docs = items(0)
retcode = items(1)
logfile = items(2)
if docs = "c" then
name = "some stuff"
else
name = "some other stuff"
end if
If retcode = 0 Then
lf.writeline "[" & now & "] " & name & " folder was already up to date."
elseif retcode = 1 then
lf.writeline "[" & now & "] " & name & " folder was updated."
seelog(logfile)
else
lf.writeline "[" & now & "] " & name & " folder update exited with robocopy error code: " & retcode
seelog(logfile)
End If
end function
'get logged in user
un = CreateObject("WScript.Network").UserName
'check for logfile, and if not exist, create
'folder1 always exists, no need to check or create
lfp = "c:\folder1\folder2\folder3\logfile1.log"
ld1 = "c:\folder1\folder2"
ld2 = "c:\folder1\folder2\folder3"
set fso = createobject("scripting.filesystemobject")
if not fso.fileexists(lfp) then
if not fso.folderexists(ld1) then
fso.createfolder(ld1)
end if
if not fso.folderexists(ld2) then
fso.createfolder(ld2)
end if
set cf = fso.createtextfile(lfp)
cf.close
end if
'open logfile (lfp variable)
'for writing (2)
'overwrite if already exists (true)
wscript.sleep 30000
'************permission denied happens on next line on lfp var*************
Set lf = fso.OpenTextFile(lfp, 2, True)
lf.writeline "[" & now & "] " & "Script started."
lf.writeline "[" & now & "] " & "Logged in user: " & un
lf.writeline "[" & now & "] " & "========================================================="
more code writing to log file and executing robocopy....
I suppose suppressing all errors is an option, but 1) I'd rather not, and 2) I'm not clear on how to accomplish that in VBScript.
ETA:
On Error Resume Next
Set lf = fso.OpenTextFile(lfp, 2, True)
On Error Goto 0
I tested this and it does break the script. lf is not set due to the error so the following lines error out with 'object required "lf"' code 800a01a8 as expected.
I don't like doing this, but my work around was to launch the .vbs from a .bat (personal preference - I like to keep everything from one job in one script so in the future I don't have to go chasing files around).
I placed a logon.bat file in my GPO as the logon script.
#echo off
echo Launching update script...
cscript c:\folder1\script.vbs
This seems to work around the (apparently false) permissions issue I was having. I'm still curious if anyone can tell me exactly why I was seeing the behavior I saw. Does the script engine write to a temp location maybe, when calling OpenTextFile (when launching directly from the GPO) that only admin users would have access to?
On Error Resume Next will ignore the error then On Error Goto 0 will turn normal error handling back on

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

VB script to run a Query

I am trying to connect command prompt through VB script and further its connecting with Oracle enviroment to execute some reports of Oracle discoverer.
But the problem is with this VB script only.
line 2: for establishing the connection.
line 7:fetching the current REQUEST_ID.
line 16:XXDIS_EXPORT_CMD_V is a view and cmd is a column.which select a value like this for corresponding REQUEST_ID.
/CONNECT DISCADMIN:"FAI Financials Intelligence"/discbi#deverp /OPENDB "1 Scheduling" /SHEET "Sheet_1" /EXPORT HTML o27673334.out /LOGFILE l27673334.log /BATCH
In the end i want to execute this cmd using VBScript.
Error coming :
"In line 32 tkgoShell was not
recognized"
This is My code:
' Process job
Set objADO =CreateObject("ADODB.Connection")
objADO.Open "Driver={Microsoft ODBC for Oracle}; CONNECTSTRING=deverp; UID=apps; PWD=apps11i;"
MsgBox "Connection Established to Server.", vbExclamation + vbOKOnly, "System"
Do While True
' Check if there is a job to process
Set moRS=objADO.execute("SELECT apps.xxdis_schedule_pkg.start_job REQUEST_ID FROM dual")
moRS.MoveFirst
msRequest = moRS("REQUEST_ID")
'MsgBox msRequest,msRequest
' If no jobs then exit
' If msRequest = "0" Then
Exit Do
' End If
loop
Set moRS=objADO.execute("SELECT cmd EXPORT_CMD FROM apps.xxdis_export_cmd_v " & _
"WHERE request_id = " & msRequest)
MsgBox msRequest,msRequest
moRS.MoveFirst
msExpCmd = moRS("EXPORT_CMD")
' write command into a temporary file
msCmdFile = "r" & msRequest & ".cmd"
dim moOutputStream,filesys,msCommand
Set filesys = CreateObject("Scripting.FileSystemObject")
Set moOutputStream = filesys.CreateTextFile(msCmdFile, True)
' Substitute $SAMBA$ and $TNS$ locally configured variables
moOutputStream.Write Replace(Replace(msCmd, "$SAMBA$", gsOutDir),_
"$TNS$", gsInstance) & vbCRLF
moOutputStream.Close
' Call Discoverer to process the command
msCommand = gsBinDir & gsDiscoExe & " /EUL " & gsEUL & " /CMDFILE " & msCmdFile
Call tkgoShell.Run (msCommand, 1, true)
If I understand your code correctly I can't see anywhere where you're actually creating the tkgoShell.
Try inserting the following 2 rows before your last line:
Dim tkgoShell
Set tkgoShell = WScript.CreateObject ("WScript.Shell")
See here for more information about Shell.Run.

VB6 - How to catch exception or error during runtime

I developed an application in VB6. In client's environment it raises runtime errors which I can't reproduce under debugger. Is there any way to get the stacktrace or location of error?
I created log file and
I used
Err.Description,Err.Source
but it gives blank values.
Please help me.
my method(......
On Error GoTo Error_Handler
.........
Error_Handler :
writeToLogFile(Err.Source,Err.Description)
You've probably done something to clear the Err object before writing to the log file. This is very, very easy to do. What you'll want to do is as soon as you detect an error has occurred, grab the error message before doing anything else. Then pass the error message to whatever logging routine you're using. E.g.:
Dim sMsg As String
On Error Goto ErrHandler
' ...code here...
Exit Function
ErrHandler:
sMsg = "Error #" & Err.Number & ": '" & Err.Description & "' from '" & Err.Source & "'"
GoLogTheError sMsg
BTW, thanks for your guys' answers helping me. I'm about half a decade late to the game of VB6. I don't do windows unless forced to. ;)
Anyhow, when doing your error checking, say among 3000 individual record query insertions, I learned a couple tricks. Consider this block of code:
'----- order number 1246-------
On Error Goto EH1246:
sSql="insert into SalesReceiptLine ( CustomerRefListID,TemplateRe..."
oConnection.Execute sSQL
sSql="SELECT TxnID FROM SalesReceiptLine WHERE RefNumber='1246'..."
oRecordset.Open sSQL, oConnection
sTxnId = oRecordset(0)
oRecordset.Close
sSql="INSERT INTO SalesReceiptLine (TxnId,SalesReceiptLineDesc,Sal..."
oConnection.Execute sSQL
EH1246:
IF Err.Number<>0 THEN
sMsg = sMsg & "Order # 1246; sTxnId = " & sTxnId & _
vbCrLf & Err.Number & ": " & Err.Description & vbCrLf
sErrOrders = sErrOrders & "1246,"
End If
On Error GoTo -1
'----- order number 1247-------
On Error Goto EH1247:
When not testing for Err.Number, you'll get a 0: on every order handled. (maybe you don't want that). The On Error GoTo -1 resets the error so that it will work again. Apparently, Err only works "once".
I wrote a php script to build the VB6 source code to run some 8000 odbc queries... :P
Do you definitely, positively have an Exit Function just above the Error_Handler:?
my method(......
On Error GoTo Error_Handler
........
Exit Sub
Error_Handler :
writeToLogFile(Err.Source,Err.Description)
"Exit Sub" should be added before you handle the Error_Handler function.....

Resources