Voodoo with DOS Batch files - visual-studio

I've created a simple batch file that kicks off my *.msi installer within our company, creating a log file of the process, then displays the log file after the installer has completed.
installAndLog.bat:
msiexec.exe /i "\\FileServer2\setup.msi" /l*v "C:\setupLog.txt"
"C:\setupLog.txt"
It works, but there are two (2) glitches that annoy me:
The black console box shows in the background the whole time the installer is running and the log file is being displayed. Q1: How do I hide that?
and
The console box will not close until the log file is no longer being viewed (i.e. notepad.exe is closed). Q2: Can I call the text file in a new process and simply exit?
I was a DOS lover back in the day, but that was too many years ago.

I don't think you can hide the console window when running a batch file. However you can use vbscript instead which will by default not create a console window.
Take the below and put it in a file with a .vbs extension:
Dim wshShell
Set wshShell = CreateObject("WScript.Shell")
wshShell.Run "msiexec.exe /i ""\\FileServer2\setup.msi"" /l*v ""C:\setupLog.txt""", 1, true
wshShell.Run "C:\setupLog.txt"
All the double double quotes are there because the entire command must be surrounded by "'s and doubling them escapes them. The the documentation for WshShell.Run for more info.

Q1 - AFAIK you can't really hide the console window.
Q2 - Use the start command. This will launch the specified program (notepad) outside of the shell. It will also prevent the shell from waiting until the application closes to continue processing the batch script.
You might be better off changing the batch script to launch the MSI installer using the start command and having the installer launch notepad to view the log file once installation is complete.

If you really want to get these batch windows away, you'll have to switch over to something else. One simple alternative could be one of the scripting languages supported by the windows scripting host.
Or you try HTA (HTML applications) see here and here.

Run the dos script as a different user by scheduled task or as a service.

Related

Using VBscript to find the column width of a console window

In a batch file I can get the width of the console window using one of the examples here:
Windows console width in environment variable
#echo off
for /F "usebackq tokens=2* delims=: " %%W in (`mode con ^| findstr Columns`) do set CONSOLE_WIDTH=%%W
echo Console is %CONSOLE_WIDTH% characters wide
Similarly, I would like to know how to get the width of the parent shell's console when I run a VBscript from a Command Prompt. If I try running the above batch file from VBscript using:
CreateObject("WScript.Shell").Run "cmd /k FindWidth.bat"
A new console opens, and the width given by FindWidth.bat is for the new console window, not the console of the parent shell.
Using VBscript I can find the process ID of the parent shell using the following method: In a vbscript, how can i get the process id of the cmd.exe in which the vb script is running. Is there a way to do something similar to find its console column width? Maybe another method can be used since the process ID is known?
EDIT UPDATES:
I thank everyone for the comments. I'll try to add some more information of what I'm trying to accomplish. I have a kind of work around already but I was hoping for a slightly better solution.
The VBscript is run from a Command Prompt directly. Unfortunately, the VBscript is most likely run from wscript.exe because that is the default on normal Windows installations. But I still want to output error messages and other messages to the console and not to a popup window.
If I could guarantee it was run with cscript, there would be no problems. Restarting the VBscript with cscript starts a new process so any messages from the newly run csript VBscript go to a new console and not the original console.
I have a solution which works but it is clumsy because it uses a batch file wrapper with the same name as the .vbs but with a .bat extension instead of .vbs extension. All the batch script does is run the VBscript using cscript. It is mentioned in this topic: In vbscript, how do I run a batch file or command, with the environment of the current cmd prompt window?
I was hoping to find a way to get rid of the batch file wrapper but now I don't think it is possible.
I was trying another workaround which allows WScript to be used. Since the process ID of the console window can be obtained, a message can be sent to the original console window by first guaranteeing it is activated with:
objShell.AppActivate(ProcessID)
Then the script can immediately send a message to the original console with:
objShell.SendKeys ":: " & WindowMessage & "{enter}"
The trick is using "::" to make the message a comment that doesn't do anything. This works okay. One small problem is that it makes the console window use the comment for the last command buffer so if the user presses the up arrow or F3 etc, the comment is shown like it was a command they typed themselves. That is annoying but since it is just a comment, no errors are produced and it isn't much of a problem.
The part that is annoying is that the message appears on the same line as a normal command and doesn't look like a proper cscript sent message. The reason I wanted the width of the console is to format the message by buffering it with the proper number of spaces so that it looks identical to a message that would have been sent from cscript. Then it would look like real stdout output except for the ":: " at the start of the message.
The script could just read the default setting for the command prompt but that will not format it correctly in a lot of cases.
If I could find a way to go to a new line with SendKeys and send the message before the PROMPT appears, that would do the same thing. Is there a character that could be sent which would start a new line before the PROMPT appears??
Is there a way of using VBscript to inject a text message into the stdout of a specific console window. Being that the process ID is known of the console that should get the stdout, is it possible for the wscript VBscript to run another batch script or another program silently which could use the Process ID to inject a message into the stdout of the original console window.
Ultimately, all I wanted was to have the VBscript file be run directly in a Command Prompt that can output messages to that same console. But to do that properly seems to require the user type "cscript scriptname.vbs arguments" instead of just "scriptname arguments" which is how it should be possible but apparently isn't! Using a batch file wrapper is another option that kind of tricks the user into running a different batch file instead of the VBscript file directly. I guess I would need to redo the script in a real computer language instead of a scripting language to make it work properly. I really don't understand why this is so difficult to accomplish with VBscript when it seems like it should be trivial.
It is a bit annoying that Windows sets VBscript to use WScript by default when WScript doesn't allow any console output at all. But CSCript can do both Windows popups and console output. Why even have WScript vs CScript distinction at all when it seems like everything can be done with CScript alone?

How to run VBScript from command line without Cscript/Wscript

I am a beginner in VBScript. I googled it & got to know that we can run VBScript from command line by executing below command:
For Example my vbscript name is Converter.vbs & it's present in folder D:\VBS.
I can run it through following methods:
CScript "D:\VBS\Converter.vbs"
OR
WScript "D:\VBS\Converter.vbs"
Now I would like to execute above VBScript without Cscript or Wscript command by simply typing the name of VBscript name i.e. Converter.
I DON'T WANT TO SPECIFY THE FULL PATH OF VBSCRIPT EVERYTIME.
Can anyone please guide me on how to do that ?
I'll break this down in to several distinct parts, as each part can be done individually. (I see the similar answer, but I'm going to give a more detailed explanation here..)
First part, in order to avoid typing "CScript" (or "WScript"), you need to tell Windows how to launch a * .vbs script file. In My Windows 8 (I cannot be sure all these commands work exactly as shown here in older Windows, but the process is the same, even if you have to change the commands slightly), launch a console window (aka "command prompt", or aka [incorrectly] "dos prompt") and type "assoc .vbs". That should result in a response such as:
C:\Windows\System32>assoc .vbs
.vbs=VBSFile
Using that, you then type "ftype VBSFile", which should result in a response of:
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
-OR-
C:\Windows\System32>ftype VBSFile
vbsfile="%SystemRoot%\System32\CScript.exe" "%1" %*
If these two are already defined as above, your Windows' is already set up to know how to launch a * .vbs file. (BTW, WScript and CScript are the same program, using different names. WScript launches the script as if it were a GUI program, and CScript launches it as if it were a command line program. See other sites and/or documentation for these details and caveats.)
If either of the commands did not respond as above (or similar responses, if the file type reported by assoc and/or the command executed as reported by ftype have different names or locations), you can enter them yourself:
C:\Windows\System32>assoc .vbs=VBSFile
-and/or-
C:\Windows\System32>ftype vbsfile="%SystemRoot%\System32\WScript.exe" "%1" %*
You can also type "help assoc" or "help ftype" for additional information on these commands, which are often handy when you want to automatically run certain programs by simply typing a filename with a specific extension. (Be careful though, as some file extensions are specially set up by Windows or programs you may have installed so they operate correctly. Always check the currently assigned values reported by assoc/ftype and save them in a text file somewhere in case you have to restore them.)
Second part, avoiding typing the file extension when typing the command from the console window.. Understanding how Windows (and the CMD.EXE program) finds commands you type is useful for this (and the next) part. When you type a command, let's use "querty" as an example command, the system will first try to find the command in it's internal list of commands (via settings in the Windows' registry for the system itself, or programmed in in the case of CMD.EXE). Since there is no such command, it will then try to find the command in the current %PATH% environment variable. In older versions of DOS/Windows, CMD.EXE (and/or COMMAND.COM) would automatically add the file extensions ".bat", ".exe", ".com" and possibly ".cmd" to the command name you typed, unless you explicitly typed an extension (such as "querty.bat" to avoid running "querty.exe" by mistake). In more modern Windows, it will try the extensions listed in the %PATHEXT% environment variable. So all you have to do is add .vbs to %PATHEXT%. For example, here's my %PATHEXT%:
C:\Windows\System32>set pathext
PATHEXT=.PLX;.PLW;.PL;.BAT;.CMD;.VBS;.COM;.EXE;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY
Notice that the extensions MUST include the ".", are separated by ";", and that .VBS is listed AFTER .CMD, but BEFORE .COM. This means that if the command processor (CMD.EXE) finds more than one match, it'll use the first one listed. That is, if I have query.cmd, querty.vbs and querty.com, it'll use querty.cmd.
Now, if you want to do this all the time without having to keep setting %PATHEXT%, you'll have to modify the system environment. Typing it in a console window only changes it for that console window session. I'll leave this process as an exercise for the reader. :-P
Third part, getting the script to run without always typing the full path. This part, in relation to the second part, has been around since the days of DOS. Simply make sure the file is in one of the directories (folders, for you Windows' folk!) listed in the %PATH% environment variable. My suggestion is to make your own directory to store various files and programs you create or use often from the console window/command prompt (that is, don't worry about doing this for programs you run from the start menu or any other method.. only the console window. Don't mess with programs that are installed by Windows or an automated installer unless you know what you're doing).
Personally, I always create a "C:\sys\bat" directory for batch files, a "C:\sys\bin" directory for * .exe and * .com files (for example, if you download something like "md5sum", a MD5 checksum utility), a "C:\sys\wsh" directory for VBScripts (and JScripts, named "wsh" because both are executed using the "Windows Scripting Host", or "wsh" program), and so on. I then add these to my system %PATH% variable (Control Panel -> Advanced System Settings -> Advanced tab -> Environment Variables button), so Windows can always find them when I type them.
Combining all three parts will result in configuring your Windows system so that anywhere you can type in a command-line command, you can launch your VBScript by just typing it's base file name. You can do the same for just about any file type/extension; As you probably saw in my %PATHEXT% output, my system is set up to run Perl scripts (.PLX;.PLW;.PL) and Python (.PY) scripts as well. (I also put "C:\sys\bat;C:\sys\scripts;C:\sys\wsh;C:\sys\bin" at the front of my %PATH%, and put various batch files, script files, et cetera, in these directories, so Windows can always find them. This is also handy if you want to "override" some commands: Putting the * .bat files first in the path makes the system find them before the * .exe files, for example, and then the * .bat file can launch the actual program by giving the full path to the actual *. exe file. Check out the various sites on "batch file programming" for details and other examples of the power of the command line.. It isn't dead yet!)
One final note: DO check out some of the other sites for various warnings and caveats. This question posed a script named "converter.vbs", which is dangerously close to the command "convert.exe", which is a Windows program to convert your hard drive from a FAT file system to a NTFS file system.. Something that can clobber your hard drive if you make a typing mistake!
On the other hand, using the above techniques you can insulate yourself from such mistakes, too. Using CONVERT.EXE as an example.. Rename it to something like "REAL_CONVERT.EXE", then create a file like "C:\sys\bat\convert.bat" which contains:
#ECHO OFF
ECHO !DANGER! !DANGER! !DANGER! !DANGER, WILL ROBINSON!
ECHO This command will convert your hard drive to NTFS! DO YOU REALLY WANT TO DO THIS?!
ECHO PRESS CONTROL-C TO ABORT, otherwise..
REM "PAUSE" will pause the batch file with the message "Press any key to continue...",
REM and also allow the user to press CONTROL-C which will prompt the user to abort or
REM continue running the batch file.
PAUSE
ECHO Okay, if you're really determined to do this, type this command:
ECHO. %SystemRoot%\SYSTEM32\REAL_CONVERT.EXE
ECHO to run the real CONVERT.EXE program. Have a nice day!
You can also use CHOICE.EXE in modern Windows to make the user type "y" or "n" if they really want to continue, and so on.. Again, the power of batch (and scripting) files!
Here's some links to some good resources on how to use all this power:
http://ss64.com/
http://www.computerhope.com/batch.htm
http://commandwindows.com/batch.htm
http://www.robvanderwoude.com/batchfiles.php
Most of these sites are geared towards batch files, but most of the information in them applies to running any kind of batch (* .bat) file, command (* .cmd) file, and scripting (* .vbs, * .js, * .pl, * .py, and so on) files.
When entering the script's full file spec or its filename on the command line, the shell will use information accessibly by
assoc | grep -i vbs
.vbs=VBSFile
ftype | grep -i vbs
VBSFile=%SystemRoot%\System32\CScript.exe "%1" %*
to decide which program to run for the script. In my case it's cscript.exe, in yours it will be wscript.exe - that explains why your WScript.Echos result in MsgBoxes.
As
cscript /?
Usage: CScript scriptname.extension [option...] [arguments...]
Options:
//B Batch mode: Suppresses script errors and prompts from displaying
//D Enable Active Debugging
//E:engine Use engine for executing script
//H:CScript Changes the default script host to CScript.exe
//H:WScript Changes the default script host to WScript.exe (default)
//I Interactive mode (default, opposite of //B)
//Job:xxxx Execute a WSF job
//Logo Display logo (default)
//Nologo Prevent logo display: No banner will be shown at execution time
//S Save current command line options for this user
//T:nn Time out in seconds: Maximum time a script is permitted to run
//X Execute script in debugger
//U Use Unicode for redirected I/O from the console
shows, you can use //E and //S to permanently switch your default host to cscript.exe.
If you are so lazy that you don't even want to type the extension, make sure that the PATHEXT environment variable
set | grep -i vbs
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.py;.pyw;.tcl;.PSC1
contains .VBS and there is no Converter.cmd (that converts your harddisk into a washing machine) in your path.
Update wrt comment:
If you 'don't want to specify the full path of my vbscript everytime' you may:
put your CONVERTER.VBS in a folder that is included in the PATH environment variable; the shell will then search all pathes - if necessary taking the PATHEXT and the ftype/assoc info into account - for a matching 'executable'.
put a CONVERTER.BAT/.CMD into a path directory that contains a line like cscript p:\ath\to\CONVERTER.VBS
In both cases I would type out the extension to avoid (nasty) surprises.
I am wondering why you cannot put this in a batch file. Example:
cd D:\VBS\
WSCript Converter.vbs
Put the above code in a text file and save the text file with .bat extension. Now you have to simply run this .bat file.
Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.
Check the answer -> Here
And here is an example:
Converter.bat
::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &#echo off
rem^ &call :'sub
rem^ &exit /b
:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b
'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester
You may follow the following steps:
Open your CMD(Command Prompt)
Type 'D:' and hit Enter. Example: C:\Users\[Your User Name]>D:
Type 'CD VBS' and hit Enter. Example: D:>CD VBS
Type 'Converter.vbs' or 'start Converter.vbs' and hit Enter. Example: D:\VBS>Converter.vbs Or D:\VBS>start Converter.vbs

cmd.exe doesn't terminate when using a .bat file

[Context: I'm trying to create a shortcut to a .bat file with a relative "Start in" path as roughly described here and here.]
cmd.exe supports the /c switch. According to the documentation, this should cause it to "carry out the command and then terminate."
But the switch seems to be ignored when the command is a .bat file.
For example, if you create a shortcut with the following Target (to a normal, non-bat command):
C:\Windows\System32\cmd.exe /c "START /d C:\temp\ notepad.exe test.txt"
Everything works as expected: Notepad opens and the console (shell) disappears. But if you replace the command above with a .bat file instead, like so:
C:\Windows\System32\cmd.exe /c "START /d C:\temp\ C:\test.bat"
(where test.bat contains only "notepad.exe test.txt") Notepad opens as before but the console sticks around like an unwanted friend. Why? And more to the point, How do I make it go away?
UPDATE: I know I can use wscript, as in this solution, but then I lose the option of having a custom icon (I'm stuck with the default .vbs icon).
The start command begins a new process for the batch file. The original cmd.exe then terminates, but leaves the new process, which hangs around because it's waiting for notepad.exe to terminate.
Change your bat file contents to:
start "" notepad.exe test.txt
Then your batch file will not wait for notepad to exit before continuing execution.
Another thing to try:
C:\Windows\System32\cmd.exe /c "START /d C:\temp\ C:\test.bat & exit"
The nuclear option would be to write a small program in the (compiled) language of your choice that launches the .bat file and then exits. Then you can give it a custom icon, and make it do whatever you like.
You might also take a look at Autoit from http://autoitscript.com as an alternative to batch. - the Run() command can do this kind of thing with better predictability. Since it makes an executable you can link this from a shortcut directly. You can also do a whole lot more of course, like run as a different user, insert delays or handle errors, that are hard to do with batch.
You don't need the full kit, just the Aut2EXE folder from the download will do.
BTW, build your exes without UPX compression as that leads to AV false positives.
I'm a little late but here is the answer.
The documentation for start states:
Syntax
START "title" [/D path] [options] "command" [parameters]
If command is an internal cmd command or a batch file then the command
processor is run with the /K switch to cmd.exe. This means that the
window will remain after the command has been run.
If start is used to execute a batch file, the opened cmd instance wont close.
You could also use call instead.
call C:\test.bat

How to disable ECHO DIALOGS for Windows Script Host running a vbs file?

Ran into a problem today. I have a Windows Server 2003 with a bunch of .bat files that essentially start .vbs scripts. Every time an ECH is used in the script I get that annoying dialog box that contains content of an echo and requires to click ENTER all the time. How can I just disable the dialogs and keep ECHOs in the command prompt window only?
Force it to run under cscript instead of wscript
If you are running the script manually, just put cscript in front of it.
Otherwise, this might give you an approach:
http://www.robvanderwoude.com/vbstech_engine_force.php
Redirect the output somewhere else, i.e.
scriptname.vbs > textfile.txt

how to hide cmd shell window?

on start up i have a bat file run routine things for me
however, the black console pops up and stays open until everything is finished....
anyway to hide it and run it in background ? so it shouldn't appear minimized or system tray.
You can use a VBS script to achieve this. Either write all your code as VBS, or call your batch file like this:
'launch.vbs
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "mybatch.bat", 0
WshShell = Null
Create a shortcut to the file. On the new shortcut: Right click -> Properties. Go to the Shortcut tab, and choose "Run: Minimized." (This is assuming you're on WinXP).
This link should help you as helped me. I used the second solution that uses a program named quiet.exe
To use, just call quiet.exe program params_if_has.
My use example: quiet.exe php script.php
You can't really do that but if you are using the scheduler to run the batch file you can select "don't interact with desktop" when creating the job.
I once had a little program which could hide windows based on their title. So my startup batch first set a unique title with title and then called the other program to hide the window with said title. Worked fine but involves a little programming.
If you don't want to go that way, then you should use the Task Scheduler as tr4656 noted.
Try renaming your file to .cmd instead of .bat.
Or, if you're executing a .exe try:
start "" "C:\Program Files\SomeProg\someprog.exe"
Note: When using "start" you have to be at a command prompt.

Resources