vbs run command no output - vbscript

Okay I created a small script to call "net file" and pump the output to a file. There are no spaces in the filenames, and everything seems okay when I run it interactively. So I run the following and I get no results and no errors:
set oWShell = CreateObject("WScript.Shell")
owshell.run "net file > C:\openfiles.txt"
Set owShell = nothing
Now if modify this just slightly to show execute the same command (and keep my command window open) it works just as expected (except it keeps the cmd window open which I can't have)
set oWShell = CreateObject("WScript.Shell")
owshell.run "%comspec% /k net file > C:\openfiles.txt"
Set owShell = nothing
It must be something obvious that I'm just missing. I only touch vbs once in a blue moon so it isn't something that I'm that used to using.
Any help would be appreciated! Thanks in advance!

You need a shell (i.e. %comspec%) to get shell features like redirection; the persisten window is what you asked for: the /k lets the shell stay open (try /c instead) and you should use the second and third parameter of the .Run method to get a hidden window (and possibly wait for the process before you zap the owShell).

Have a look at Run. Changing
owshell.run "%comspec% /k net file > C:\openfiles.txt"
to
owshell.run "%comspec% /c net file > C:\openfiles.txt", 0, FALSE
This will hide the cmd and carry on with the rest of the script... If you want to wait for the command to finish, change FALSE to TRUE.
Also keep in mind that some machines are funny about letting you write files directly to C:\. Possibly create a test folder and write to there instead!

Related

Close opened cmd window from .bat file open application and execute file

I have a .bat file which opens an application and then executes a file that runs a job within the application. I cannot close the cmd window which opens when the task runs in windows task scheduler.
"C:\Proram Files (x86)\ \ \ Robot.exe" execute =f "S:\dept\ Team\ \ YearEndAudit\Main.xaml"
Any assistance would be much appreciated.
Regards,
Jeff
I may have misunderstood you, but what I understood was:
You are opening an executable with your CMD but are unable to close
the CMD after that.
I'm pretty sure that this amount of information is more than enough to solve your case, but we have very little data anyway, and the data is confusing. Please try to improve on your next post.
What is happening is that you are probably just putting the name of the program / script in your CMD, like:
program.exe
This causes the program to depend on the CMD to run, and also prevents the window from being closed. You can solve this problem using "start" at the beginning of everything, such as:
start "" "X:\Path\program.exe" execute -f "everythingyouwants"
You may need to be in the program folder, since some programs done lazily may consider your current location as the default location and may not find the dependencies they need.
If you care to stay in the folder you are currently in, you can use:
pushd "thepath\ofthe\program"
start program.exe
popd
Another way is to hide the window creating a script in VBS, such as:
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c X:\YOURSCRIPTPATH\YOURSCRIPTNAME.bat/cmd"
oShell.Run strArgs, 0, false
However, if the path also needs quotes, we can have conflicts. The above is not ideal but may help sometime.
If none of this works for you, let us know.
Hope this helps,
K.

Run batch file in background

I've got a batch file that I want to run in the background whenever the system (Windows 2007) is turned on. The batch file monitors the task list for a given program, and when it sees that it's shut down, prompts the user to de-licence it.
I'm currently trying to do this without converting the batch file into either an executable or Windows service file.
I've found more online references than I can count which tell me that I should use "start /b file.bat" to run the batch file in the background, but this doesn't work for me, it just starts up the batch file in the same cmd line window that I'm using.
Can anyone suggest either what's going wrong, or even better; a nice simple way for me to get the batch file to run ion start up (I cannot use a GUI as I have to roll this out to several computers remotely)
Thanks
You could make a shortcut to your batch file and place the shortcut in your Startup Programs directory:
C:\Users\\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Since you have to roll this out to several computers remotely, you should be able to copy the batch file to the startup programs directory over the network assuming the remote machines have WinRM enabled and your account has adequate permissions.
If you want this batch file to run in the background at start up, you could reference your batch file from a VBScript (instead of using the batch file's short cut) and set the VBscript to run in invisible mode:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\path\to\your\batchfile.bat" & Chr(34), 0
Set WshShell = Nothing
Just give this vbscript file the .vbs extension.
If the program you are concerned about is a GUI program (ie non console) just wait for it to exit. Batch waits for GUI programs to exit (but not when started interactively).
notepad
echo My notepad exited
Start /b says to start program in same window. See Start /?. Also Start is usually the wrong command to be using. It starts programs in abnormal ways. See end of http://stackoverflow.com/questions/41030190/command-to-run-a-bat-file/41049135#41049135 for how to start programs.
This is a VBS file.
This monitors for notepad exiting, pops up a messagebox, and restarts notepad.
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery("SELECT * FROM Win32_ProcessStopTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
msgbox objReceivedEvent.ProcessName
If lcase(objReceivedEvent.ProcessName) = lcase("Notepad.exe") then
Msgbox "Process exited with exit code " & objReceivedEvent.ExitStatus
WshShell.Run "c:\Windows\notepad.exe", 1, false
End If
Loop
This should use less battery power and CPU cycles. Batch files are read line by line so make VERY poor background tasks.
If the program you are concerned about is a GUI program (ie non console) just wait for it to exit. Batch waits for GUI programs to exit (but not when started interactively).
notepad
echo My notepad exited

running .bat in powershell script without opening any windows

I have written a PowerShell script that is going to interpret a mail's body for command's and create a .bat file to execute the commando's it found.
This script works, but the one big issues is that whenever is executes the .bat file, a command-prompt window flashes over the screen real quick. I was wondering if it's possible to prevent this from happening?
My code:
$m.Body | Out-File cmd.bat -Encoding ascii -Append
.\cmd.bat | Out-File results.txt
Is there any command of property i have to set?
Thanks.
I realize this question is more than 2 years old at the time I write this however there is still no official answer. Although I am very new to PowerShell, I think I have a more pure Powershell answer than using vbscript or COM.
Use Invoke Command:
Invoke-Command {cmd.exe /c cmd.bat} | Out-File results.txt
That Should do the trick. This will shell to cmd.exe and the /c will self terminate the shell on completion. It will run within the current shell so no new window will open.
Answers and information can be found here.
From there, the selected answer, in case the link goes stale:
Save the following as wscript, for instance, hidecmd.vbs after replacing "testing.bat" with your batch file's name.
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c testing.bat"
oShell.Run strArgs, 0, false
The second parameter of oShell.Run is intWindowStyle value indicating the appearance of the program's window and zero value is for hidden window.
The reference is here http://msdn.microsoft.com/en-us/library/d5fk67ky.aspx

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

Hide Command Window of .BAT file that Executes Another .EXE File

This is a batch file in Windows.
Here is my .bat file
#echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
"C:\ThirdParty.exe"
This works fine except the .bat file leaves the command window open the whole time the "ThirdParty" application is running.
I need the command window to close.
I would use the short-cut for the application but I must be able to run this copy command first (it actually changes which data base and server to use for the application).
The ThirdParty application does not allow the user to change the source of the db or the application server.
We're doing this to allow users to change from a test environment to the production environment.
Using start works for me:
#echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe
EDIT: Ok, looking more closely, start seems to interpret the first parameter as the new window title if quoted. So, if you need to quote the path to your ThirdParty.exe you must supply a title string as well.
Examples:
:: Title not needed:
start C:\ThirdParty.exe
:: Title needed
start "Third Party App" "C:\Program Files\Vendor\ThirdParty.exe"
Create a .vbs file with this code:
CreateObject("Wscript.Shell").Run "your_batch.bat",0,True
This .vbs will run your_batch.bat hidden.
Works fine for me.
Using start works fine, unless you are using a scripting language. Fortunately, there's a way out for Python - just use pythonw.exe instead of python.exe:
:: Title not needed:
start pythonw.exe application.py
In case you need quotes, do this:
:: Title needed
start "Great Python App" pythonw.exe "C:\Program Files\Vendor\App\application.py"
Try this:
#echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe
exit
Great tip. It works with batch files that are running a java program also.
start javaw -classpath "%CP%" main.Main
You might be interested in trying my silentbatch program, which will run a .bat/.cmd script, suppress creation of the Command Prompt window entirely (so you won't see it appear and then disappear), and optionally log the output to a specified file.
Or you can use:
Start /d "the directory of the executable" /b "the name of the executable" "parameters of the executable" %1
If %1 is a file then it is passed to your executable. For example in notepad.exe foo.txt %1 is "foo.txt".
The /b parameter of the start command does this:
Starts an application without opening a new Command Prompt window. CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.
Which is exactly what we want.
I haven't really found a good way to do that natively, so I just use a utility called hstart which does it for me. If there's a neater way to do it, that would be nice.
Using Windows API we can start new process, a console application, and hide its "black" window. This can be done at process creation and avoid showing "black" window at all.
In CreateProcess function the dwCreationFlags parameter can have CREATE_NO_WINDOW flag:
The process is a console application that is being run
without a console window. Therefore, the console handle
for the application is not set. This flag is ignored if
the application is not a console application
Here is a link to hide-win32-console-window executable using this method and source code.
hide-win32-console-window is similar to Jamesdlin's silentbatch program.
There is open question: what to do with program's output when its window does not exist? What if exceptions happen? Not a good solution to throw away the output. hide-win32-console-window uses anonymous pipes to redirect program's output to file created in current directory.
Usage
batchscript_starter.exe full/path/to/application [arguments to pass on]
Example running python script
batchscript_starter.exe c:\Python27\python.exe -c "import time; print('prog start'); time.sleep(3.0); print('prog end');"
The output file is created in working directory named python.2019-05-13-13-32-39.log with output from the python command:
prog start
prog end
Example running command
batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C dir .
The output file is created in working directory named cmd.2019-05-13-13-37-28.log with output from CMD:
Volume in drive Z is Storage
Volume Serial Number is XXXX-YYYY
Directory of hide_console_project\hide-win32-console-window
2019-05-13 13:37 <DIR> .
2019-05-13 13:37 <DIR> ..
2019-05-13 04:41 17,274 batchscript_starter.cpp
2018-04-10 01:08 46,227 batchscript_starter.ico
2019-05-12 11:27 7,042 batchscript_starter.rc
2019-05-12 11:27 1,451 batchscript_starter.sln
2019-05-12 21:51 8,943 batchscript_starter.vcxproj
2019-05-12 21:51 1,664 batchscript_starter.vcxproj.filters
2019-05-13 03:38 1,736 batchscript_starter.vcxproj.user
2019-05-13 13:37 0 cmd.2019-05-13-13-37-28.log
2019-05-13 04:34 1,518 LICENSE
2019-05-13 13:32 22 python.2019-05-13-13-32-39.log
2019-05-13 04:55 82 README.md
2019-05-13 04:44 1,562 Resource.h
2018-04-10 01:08 46,227 small.ico
2019-05-13 04:44 630 targetver.h
2019-05-13 04:57 <DIR> x64
14 File(s) 134,378 bytes
3 Dir(s) ???,???,692,992 bytes free
Example shortcut for running .bat script
Target field:
C:\batchscript_starter.exe C:\WINDOWS\system32\cmd.exe /C C:\start_wiki.bat
Directory specified in Start in field will hold output files.
You can create a VBS script that will force the window to be hidden.
Set WshShell = WScript.CreateObject("WScript.Shell")
obj = WshShell.Run("""C:\Program Files (x86)\McKesson\HRS
Distributed\SwE.bat""", 0)
set WshShell = Nothing
Then, rather than executing the batch file, execute the script.
run it under a different user. assuming this is a windows box, create a user account for scheduled tasks. run it as that user. The command prompt will only show for the user currently logged in.
Compile the batch file to an executable using Batch2Exe http://www.f2ko.de/programs.php?lang=en&pid=b2e.
Use the "Invisible Window" option.
To make the command window of a .bat file that executes a .exe file exit out as fast as possible, use the line #start before the file you're trying to execute. Here is an example:
(insert other code here)
#start executable.exe
(insert other code here)
You don't have to use other code with #start executable.exe.
I used this to start a cmd file from C#:
Process proc = new Process();
proc.StartInfo.WorkingDirectory = "myWorkingDirectory";
proc.StartInfo.FileName = "myFileName.cmd";
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.Start();
proc.WaitForExit();
Please use this one, the above does not work. I have tested in Window server 2003.
#echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
Start /I "" "C:\ThirdParty.exe"
exit
So below vbscript will launch the cmd/bat file in hidden mode.
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
'MsgBox(strFolder)
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & strFolder & "\a.bat" & Chr(34), 0
Set WshShell = Nothing
Now, only app window will be visible, not the cmd.exe window
This is an easy work around for those who are fine with a dirty solution. Press win+tab, drag and drop the bat file to a new desktop and forget about it.
I occasionally will make a bat file that I'll rarely use, and it is kind of a drag to have to use tools to make the window hidden. This is no more complicated than it needs to be for me.

Resources