Running master bat file in invisible mode - batch-file

I have a master.bat file which has...
call file1.bat
call file2.bat
call file3.bat
call file4.bat
I want to schedule it on my Windows server 2008 to run in silent/invisible mode.I'm looking for some way to run this master.bat without anything visible to the user (no window, CMD interface ,no taskbar name etc..)
I don't want to install any batch to exe software.
I tried by changing the User running the task to "SYSTEM" and it has the work done but I can't do this in actual.
I have found that Windows Script Host’s Run Method allows you to run a script in invisible mode as.....
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Batch Files\master.bat" & Chr(34), 0
Set WshShell = Nothing
but no more file please :) any other suggestion for this.
EDIT1
Considering the limited options available..it would be OK to use Windows Script Host’s Run Method,but how i can schedule master.vbs in task scheduler.. ?

For an extended view of it, check for hybrid batch / vbscript / javascript files here in stackoverflow.
Save this as master.cmd and adapt as needed.
#if (#This==#IsBatch) #then
#echo off
rem **** batch zone *********************************************************
rem Check if started from javascript part of script.
rem We are checking an environment variable set from javascript part.
if "%_run_hidden_%"=="true" (
goto startBatchWork
)
rem if not started from javascript, call javascript part to restart batch.
wscript //E:JScript "%~dpnx0"
exit /b
:startBatchWork
rem Here starts the real work of the batch file
msg %username% "Batch file running hidden"
rem End of batch area. Ensure batch ends execution before reaching
rem javascript zone
exit /b
#end
// **** Javascript zone *****************************************************
// Instantiate the needed component to interact with Shell
var shell = WScript.CreateObject('WScript.Shell');
// Set the environment variable that the batch part will check to know
// it's running hidden
shell.Environment('Process').Item('_run_hidden_')='true';
// start the batch part of the script calling %comspec% with the current
// script as parameter, hidden (0) and not waiting for it to end (false)
shell.Run('"' + shell.ExpandEnvironmentStrings('%comspec%') + '" /c "' + WScript.ScriptFullName + '"', 0, false );
// All done. Exit
WScript.Quit(0);

CMDOW is a tool that will allow the batch to run hidden.
It is flagged as a hack tool by various AV programs.

Related

Run Exe from Batch and Set Environment Variable for a Return Value

How can I get an executable (.exe) to run from a batch process and get a return value in an environment variable.
Inside the batch file, I tried using
START /W /B MyProgram.exe
and -
Call MyProgram.exe
Documentation that I found at https://ss64.com/nt/start.html says using /W and /B should start the exe in the same window and wait for it to finish.
The same source says that using CALL will start the exe in the same environment and changes to variables will be preserved in the batch process that started it.
In the Visual Basic program, I tried both of the following paramaters in the Environment.SetEnvironmentVariable statement
EnvironmentVariableTarget.Process (variable remains blank)
EnvironmentVariableTarget.User (this works but the environment variable remains persistant in the user's environment variables, thereafter even after closing all cmd windows.
I definitely would like to set an environment variable inside the exe because it seems so simple. Is there a way to make this work?
My test batch file is as follows:
#echo off
REM This is a test to see if a bat file can start another program (a compiled visual basic program)
:: and use an environment variable to return a value (i.e., a short string or integer).
REM To return a value, the compiled visual basic program uses the following commmand:
:: Environment.SetEnvironmentVariable("exeReturn", sReturn, EnvironmentVariableTarget.Process)
setlocal EnableDelayedExpansion
REM EnableExtensions is set by default
title GetReturnValue_Test
set "exeReturn="
Start /W /B MyProgram.exe &REM The exe sets %exeReturn% for return value
echo exeReturn = %exeReturn%
pause
endlocal
exit
The specific snippet inside the Visual Basic file is:
lHnd = FindWindow(vbNullString, sCaption)
If lHnd = 0 Then
sReturn = "Window not found"
Environment.SetEnvironmentVariable("exeReturn", sReturn, EnvironmentVariableTarget.Process)
Exit Sub
End If
Actually, the parameter for setting the User scope environment variable did not show any change or setting of the variable until I start a new cmd window.
Sincerely SloppyCoder
The setting EnvironmentVariableTarget.Process cannot work because the VB application is running in its own process, which is a separate process to the one that your batch file is running in. A process is unable to change the environment table of another process.
The setting EnvironmentVariableTarget.User changes the setting in the Windows Registry, from which the process cmd.exe reads and initializes the environment table when a new Command Prompt window is started.
Basically, your VB application cannot set or change any environment variables belonging to your batch file.
The way to return a string from a subprocess back to its parent process is to print that string (which means your VB application must be configured as a console application), and your batch file can read its output using the FOR /F command (type for /? for help).
Thanks for all the help. I had to hack a bit and the following got the value I am going for.
FOR /F "tokens=3" %%a in ('REG QUERY HKCU\Environment /V exeReturn') DO (
Set "exeReturn=%%a"
)
Thanks, again

Open, wait, save, close, and copy a file using Windows batch file commands

With my .bat I would like to:
open the xlsx file,
waiting 2 min,
close the file with save options
copy this file to another folder.
For now I can copy and paste the file, but I don't know how to open it, with a cmd function, and save it.
Thank you for your help.
My code is :
#echo off
cmd "O:\XXXX\*.*"
xcopy/y "O:\XXXX\*.*" "O:\XXX\"
pause
Marie (TooLong;ToRead) in disjointed comments
I suggested, A simpler alternative method to do what you need on this
occasion is to use a simple command line tool see Orlandos Sendkeys
Utility (the example is almost what you want to do)
download sendkeys from cpap.com.br/orlando
see how the demo runs
open excel with a blank sheet and at a CMD> run this demo string
SendKeys.exe 1.5 10 "Microsoft Excel" "Hello!~{PAUSE 2}After 2s.~{PAUSE 2}%(FS)~"
adapt to your own version of excel keys since the %(FS) is ALT File Save in English
you replied
#KJ Thank you, KJ, unfortunately I can't download Orlando with my PC.
So we continue to doing it in a more dirty fashion, but you still need a means to save the file by invoking an autosave which would most easily be done using an extended excel macro in your source .xlsm, anyway
after all these changes your non working file should now be replaced in your question as
#echo off
start "Excel Running" /MIN EXCEL.EXE "\\XXX\Fichier.xlsm"
REM add a delay of **2 minutes !** whilst sheet recalculates before saving a copy
timeout 120
REM copying a file that has NOT been saved using keys at this point will NOT
REM be what you really need to solve your problem unless you use a macro ?
REM see Later
xcopy/y "\\XXX\Dossier_avant*.*" "\\XXX\Dossier_apres\"
REM add a 3 second delay to check above worked but is not really needed
timeout 3
REM temporary for debugging. Later just REM it out
TASKLIST /M |Find /i "exce"
REM this line should be working with either a SUCCESS: or ERROR:
TASKKILL /T /F /IM excel.exe
REM keep this line for seeing errors above, once happy, it can become REM PAUSE
PAUSE
I think that IF you are constrained (by IT policy) to the command line it is best you write your own autosaving macro, however, MY problem is I dont know if you need it for more than one input.xlsm.
So save this as OpenRunSaveExit.vbs in your working folder where your .bat is. There is a reason I did NOT use spaces or & in the name for a later step.
Set WshShell = WScript.CreateObject("WScript.Shell")
' You may need to include the path to excel.exe if it is a portable version like mine
WshShell.Run "EXCEL.EXE "+"\\XXX\Fichier.xlsm", 9
' 120000 milli-seconds = 2 minutes
WScript.Sleep 120000
' These are the English key combinations for ALT+File+Save . SO alter or remove if not needed
WshShell.SendKeys "%FS"
' These are the English key combinations for ALT+File+eXit . SO alter if needed for french excel
WshShell.SendKeys "%FX"
' Lets us wait 2 seconds for clean closure
WScript.Sleep 2000
As Peter has pointed out in his answer you need to /WAIT before xcopy and depending on how your vbs file handling is set-up you may not need Wscript in the start line
NOW replace your .bat with this
#echo off
start /WAIT Wscript OpenRunSaveExit.vbs
xcopy/y "\\XXX\Dossier_avant*.*" "\\XXX\Dossier_apres\"
pause
And check it runs without the need for taskkill.
Finally why use a 2-4 line .bat since a desktop shortcut would potentially be easier to use. So make a shortcut for the .vbs file (right click the .vbs, and in English its Create Shortcut) and wherever it is built move it to your desktop.
Then change the properties like this (where & has a special meaning so the .vbs filename must NOT have spaces or &.)
%comspec% /c "start /wait wscript.exe OpenRunSaveExit.vbs & xcopy/y "\\XXX\Dossier_avant*.*" "\\XXX\Dossier_apres\" & pause"
P.S. I forgot to add Peters start / wait in this image until later
You can't interact with Microsoft Excel (or most of other programs) through Batch unless they provide such an interface. There is however an option to do it with VBS i.e. via an interface Microsoft Excel supports for interacting with that software.
For just opening the program check start command e.g.:
start /B excel.exe <filename>
then you can wait for the user to both edit and save the file for two minutes or also utilize pause if you don't want to introduce a race condition between saving and copying with xcopy.
Alternatively use start like this:
start /WAIT /B excel.exe <filename>
so the opened file blocks the operation and once it closes (no edit or saving by the user guaranteed) then it'll unblock and xcopy would take place without any time-dependent feature.

Check if a process is closed/not running, then restart the application

Below is the script I am using to detect if my application is being closed. If it is closed the application will restart again. The application should run in the background as I am running this on startup.
run.bat
#echo off
:Restart
start "AppNAME" /wait "C:\Program Files (x86)\App\App.exe"
goto Restart
How can I hide the command windows after running the .bat file?
As per your requirement here is a vbs file that will run the batch file in background.just past the vbs file in startup and the batch file somewhere else.
REM 0 = hide window, 1 = show window (useful for debugging)
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run """" & "file.bat" & """" & sargs, 0, False
Set WshShell = Nothing

Task Scheduler not running interactive batch file/ How to make batch file non interactive

I am trying to run a batch file with task scheduler.
The batch file is utilizing SecureFX to transfer a file between servers via cmd line. The problem is the command opens a cmd window and displays info about the file transfer. I think task scheduler will not run this correctly in 'Run whether the user is logged in or not' mode because of the open cmd window.
The thing is I need it to run in 'Run whether the user is logged in or not' mode.
I have tried using vbs script with the following:
Set Shell = CreateObject("Shell.Application")
Shell.ShellExecute "my.bat", , , "runas", 0
This when run by itself does the trick, .bat runs no cmd window, but when run through task scheduler I get a 0x41301 result, which apparently means the task is already running, but the task was not running beforehand.
Contents of my.bat:
#echo off
for /f "tokens=1-4 delims=/ " %% in ('date /T') do set MyDate=%%a%%b%%c
for /f "tokens=1-4 delims=: " %%a in ("%TIME%") do set MyTime=%%a%%b%%c
set LOGFILE=D:\logfilelocation\sfxcl_log_%MyDate%_%MyTime%.txt
sfxcl /NOPROMPT /LOG "%LOGFILE%" D:\path_to_files_for_transfer\rt_*.zip sftp://user:password#hostname//destinationFolder:/
Task Scheduler Settings:
User: System
Run with Highest Privileges - On
Run whether user is logged on or not - On
Triggered daily - every day 09:00
Actions, in Program/script field:
D:\location_bat_file\my.bat
Add Arguments and start in fields are empty.
The location of the batch and vbs files I am trying to use are local.
Can someone help with this please?

Running a batch (.bat) file from a VB macro (.vbs)

I am having issues getting a simple batch file (opening command prompt) to run from a vbs macro, I know this question gets asked a lot and I have tried many different suggested solutions for this without success. I am using notepad ++ to run the scripts/VB code for testing.
I have verified that the .bat file will execute correctly by itself, any suggestion on how to get this to work correctly would be greatly appreciated.
Here is my code for each instance.
VB CODE:
Sub CallBATCH()
Dim argh As Double
argh = Shell.Run "C:\Temp\cmdPrompt.bat"
End Sub
BATCH FILE:
start cmd.exe /k
EDIT: The following is the .bat file that I actually intend on calling up:
#echo OFF
title AutoCAD DWG Duplicator
color 0a
:start
set /P TemplateName=Please enter the template name you wish to copy:
set /P NumberOfCopies=Please enter how many copies you wish to make:
set Pathname="<filepath>"
cd /d %Pathname%
:init
for /L %%f in (1,1,%NumberOfCopies%) do copy %TemplateName%.dwg C:\Temp\%%f%TemplateName%.dwg
You seem to be calling a .BAT file that in turn opens a command prompt with START. I'm unclear on why you need the .BAT at all.
Dim oShell
Set oShell = WScript.CreateObject ("WScript.Shell")
oShell.run "cmd.exe /K"
Set oShell = Nothing
The /K parameter will open the command prompt window and keep it open. You've supplied no parameters for START and no commands to execute when the command prompt opens so this should do what you are looking for. More at: Run Method (Windows Script Host)

Resources