running .bat in powershell script without opening any windows - 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

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.

can a vbscript hide the console that launched it?

I am launching from the command line a vbscript like this:
cscript.exe myscript.vbs
can I add something inside myscript.vbs to hide the console that launched it?
Is this a batch file?
If so, if that's the only line, you can put
EXIT
after your code and it will close the console once the vbscript opens.
As for hiding the console, you can run the batch from a vbs as shown here: http://www.howtogeek.com/131597/can-i-run-a-windows-batch-file-without-a-visible-command-prompt/
In general you can minimize a Program from Vbscript by using sendkeys and sending the sequence ALT+Space + whatever key is the shortcut for minimize in your local language. (You can check this in the GUI by pressing ALT+Space and looking for the underlined character in the minimize option)
In german and english this would be
wso.SendKeys "% n"
However this method is buggy with cmd and will not work since Windows XP. So the best workaround I found is a horrible hack where you use a call to powershell.exe.
The question for you is whether your program immediately steals the focus of the hosting cmd.exe or not. If not you can just insert
Set wso = CreateObject("WScript.Shell")
wso.SendKeys "powershell -windowstyle minimized -command """"{ENTER}"
If you somehow lose the focus on the cmd, you have to regain it. You could do that by using:
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
' WQL uses \ as escpae char so we need to escape it with an additional \
wmiScriptName = Replace(wscript.ScriptFullName, "\", "\\")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where CommandLine like '%" & wmiScriptName & "%'")
For Each objProcess in colProcesses
wso.AppActivate objProcess.ProcessId
wso.SendKeys "powershell -windowstyle minimized -command """"{ENTER}"
Next
This will minimize all cmds that have the script running so it should not be started multiple times.. The WQL query is also not perfect, so if you edit the script in notepad for example it will detect this as well and send keys there... If this is a use case you think will happen you have to be more exact with your WQL query (include processname cscript.exe or something)
It is quite a hack but I could not think of any other way of doing this in vbscript only (sadly one external call is necessary but no code executed and powershell.exe should be present everywhere). If you could do the whole script in powershell for example there would probably be better methods.

Tracking PID in batch file and closing cmd when PID closes

I have a batch file that starts a HTML file from command line in whatever is the default browser:
start filename.html
I am looking for some way to find out the ID of the spawned process (firefox, ie, chrome) and track the PID in order to shut down the cmd window when the process is complete.
Basically, the process would ideally go like this: start html, find PID of last spawned process, watch the PID, when PID closes - CMD will exit
I have tried searching around for this and found a way to find the pid of a process but not how to track until exit.
Is it possible to do this in a BAT file? Any assistance would be lovely. Thanks!
start filename.html
exit
try this. but however what i know is this that once the process is complete cmd closes on its own.
OR
u can directly run your file without opening the cmd black window try this below script save it as example.vbs and replace testing with ur batch filename and then run this example.vbs file instead of batch file.
Set oShell = CreateObject ("Wscript.Shell")
Dim strArgs
strArgs = "cmd /c testing.bat"
oShell.Run strArgs, 0, false

vbs run command no output

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!

Start a process in a new window from a batch file

I have written a batch file (.bat) in windows. I want to execute a particular process in a new window. How do I do this?
Example
a.py -s 3 -l 5
b.py -k 0 -> I want to start this in a new window and let the original batch file continue
C:\program.exe
...
....
Use the start command:
start foo.py
or
start "" "c:\path with spaces\foo.py"
start "title" "C:\path\to\file.exe"
I would highly recommend inserting a title so that you can call that title later via the TASKKILL command if needed.
TASKKILL /im title
The solutions below are for calling multiple files in the same window; this question has been answered already so I am just adding my 2 cents.
If you are working with a master batch file that calls multiple other batch files, you would use the "call" command. These aren't processes, though.
Within the other batch files you can call the "start" command to start them in separate windows.
master.bat
call myCoolBatchFile1.bat
call myCoolBatchFile2.bat
call myCoolBatchFile3.bat
If you are using Windows Powershell, you can use the Start-Process command.
myPowershell.ps1:
#silent install java from java exe.
$javaLogLocation = "[my log path here]"
$javaFileName = "[javaInstaller file name here].exe"
$process = "$javaFileName"
$args = "/lang=1033 /s /L $javaLogLocation"
Start-Process $process -ArgumentList $args -Wait
For more info on the start command and its usages, as well as other scripting tech:
https://ss64.com/nt/start.html
As per the requirement, we can follow up like this. As I was doing an automation work for my office purpose. So I need to create a process for a certain time, & after that I have to kill the service/ process.
So What I did,
For start a process:
**`start "API" C:\Python27\python.exe`**
Then I tried with my all other works & tasks. After that I need to kill that process. So That I did,
**`taskkill /F /IM python.exe`**
After killing the process, outcome ran smoothly.

Resources