Run batch CODE in a vbscript file - windows

I am trying to make a vbscript file that can run batch code (Note: Not a batch file, but batch code)
The code, which works in a batch file:
IF EXIST "%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms" (
"%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"
) ELSE (start /b "" cmd /c del "%~f0"&exit /b)
I can make the vbscript code almost do what I want using:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\myscript.bat" & Chr(34), 0
Set WshShell = Nothing
Now I would like to combine these two pieces of code into one file, so something along the lines of:
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Exec "IF EXIST ""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"" (""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"") ELSE (start /b """" cmd /c del ""%~f0""&exit /b)"
Set WshShell = Nothing
However when I run this code I get The system cannot find the file specified. This is expected, since Exec (or Run, or Execute) runs a batch file and not batch code. So, is there a command similar to Exec that will run batch code and not a batch file?
Some extra info that I don't think is necessary to a solution (But included for the sake of completedness):
This code is placed in the startup folder
The code is created in C# in order to run a ClickOnce application on startup
The reason I want to use vbscript is that the batch file opens a cmd window for a second, which is undesirable. My understanding is that the line Set WshShell = Nothing will make the command run invisibly
I have tried including >nul at the end of each line of the batch file, since I read that it will stop the output. This did not work for me.
It is theoretically possible for this to work by using both a .bat and a .vbs file, but this would require putting the .bat file in some other directory and feels generally hackish
I am open to other solutions besides vbscript, provided they can check if the .appref file exists, run the file if so, and delete itself if the file doesn't exist. This may be trivial in vbscript but I've never used vbscript before.
EDIT:
According to #Jason's comment, I have modified the code as follows. Now it runs with no output and without running my app (AKA it doesn't do $#!+)
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run "cmd.exe /C ""IF EXIST ""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"" (""%appdata%\Microsoft\Windows\Start Menu\Programs\MyManufacturer\MyClickOnceApp.appref-ms"") ELSE (start /b """" cmd /c del ""%~f0""&exit /b)", 0
Set WshShell = Nothing

The problem are the string in the path ! like this it work :
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "cmd /c if exist test1.txt (echo ok & del test1.txt & pause) else (echo ko & pause)"
Try to work with 8.3 format. To resolve the composed-name and don't use string.
But if you're programming in VBS why do you want to use batch code in it ?
If you want to use both make a .BAT file. Or generate it from you're VBS and call it.

Here is a example:
you have a batch called regex.bat :
#echo off &setlocal
for /f "tokens=1* delims=:" %%i in (
'netsh wlan show interfaces ^| findstr /rxc:"[ ]* SSID [ ]*: ..*"'
) do for /f "tokens=*" %%k in ("%%j") do set "SSID=%%k"
echo %SSID% > regex.txt
the vbs looks like this:
Set WshShell = WScript.CreateObject( "WScript.Shell" )
WshShell.Run "regex.bat",0,True
This works for me fine. No cmd-Windows comes up. Hope this helpes you

Related

I want to run a 3rd party .exe file from a .bat file without a visible command prompt

Firstly I have created VBScript to run a batch file without a visible command prompt.
Following is the code:
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run Chr(34) & ("D:\Intouch_Printer_SW\spool12\spltotext.bat") & Chr(34), 0
Set WshShell = Nothing
Following is my batch file code to run a third party .exe file.
for %%f in (C:\WINDOWS\system32\spool\PRINTERS\*.SPL) do (
echo %%~nf
start "" D:\Intouch_Printer_SW\spool12\spool.exe "C:\WINDOWS\system32\spool\PRINTERS\%%~nf.SPL" "Intouch Printer"
)
Whenever I run my .vbs code a console window pops up, I want to do all of it without a visible command prompt.
I think I am getting a black window due to this snippet:
start "" D:\Intouch_Printer_SW\spool12\spool.exe "C:\WINDOWS\system32\spool\PRINTERS\%%~nf.SPL" "Intouch Printer"
start opens the command in a new window. It isn't required for running console applications, so you can simply remove it:
for %%f in (C:\WINDOWS\system32\spool\PRINTERS\*.SPL) do (
echo %%~nf
D:\Intouch_Printer_SW\spool12\spool.exe "C:\WINDOWS\system32\spool\PRINTERS\%%~nf.SPL" "Intouch Printer"
)
In addition I would recommend running the batch script synchronously from the VBScript (3rd argument to the Run method set to True), to avoid undesired side effects should anyone ever modify the VBScript.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run """D:\Intouch_Printer_SW\spool12\spltotext.bat""", 0, True

WScript v/s CScript

I have query related to this topic. Here is my script. I'm using below script to edit users on HP ILo board, it works fine, no error at all.
BUT here I can see cmd prompt, how do I run it in silent mode, i.e I do not want to see any cmd prompt, because I use BMC, so let it run in background, I will check the output later.
As you said I can simply change WScript to CSrcipt. But that does not work.
Any help please, please let me know where to modify.
Set wshShell = WScript.CreateObject ("WScript.Shell")
WshShell.Run "cmd.exe /v:on /k (set MYDIR=C:\Program Files\HP\hponcfg) & cd /d ""!MYDIR!"" & HPONCFG.exe /f Add_User1.xml /l log1.txt > output1.txt"
WScript.Sleep 1*60*1000
WshShell.Run "cmd.exe /v:on /k (set MYDIR=C:\Program Files\HP\hponcfg) & cd /d ""!MYDIR!"" & HPONCFG.exe /f Add_User2.xml /l log2.txt > output2.txt"
Set wshShell = Nothing
Wscript.quit
Regards
Use the second parameter of the .Run method
intWindowStyle Optional. Integer value indicating the appearance of
the program's window. Note that not all programs make use of this
information.
As I know nothing about BMC, I'd start with minimized (7, 6) before I'd try hidden (0).

How can I hide ms-dos window when running a .bat file?

I am running a .bat file for my script (Scheduled Tak (CronJob)) per minute.
When it runs, windows command prompt appears for a fiction of time.
My batch code like this;
#ECHO OFF
C:\wamp\bin\php\php5.4.3\php.exe -f "C:\wamp\www\tst\index.php"
How can I hide this window when it run?
Use a VBScript
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("C:\yourbatch.bat"), 0, True
Run that which will run your batch file hidden.
I don't like the VBScript solution.
Download and copy nircmd.exe to your %systemroot%\system32 folder, then add this command to first line of your batch:
nircmd.exe win hide ititle "cmd.exe"
You can also change the title of your batch file terminal window by title command to avoid from hiding all cmd windows, like this:
title MyBatch
nircmd.exe win hide ititle "MyBatch"
This VBScript creates a copy of your batch file in %Temp%, executes it silently and deletes it afterwards
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
Dim tempfolder
Const TemporaryFolder = 2
Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir = WshShell.CurrentDirectory
batch = "#ECHO OFF" & vbCrLf & _
"C:\wamp\bin\php\php5.4.3\php.exe -f C:\wamp\www\tst\index.php"
Set tempfolder = fso.GetSpecialFolder(TemporaryFolder)
WshShell.CurrentDirectory = tempfolder
i=1
n=0
While n <> 1
If (fso.FileExists(i&".bat")) Then
i = i + 1
Else
n = 1
End If
Wend
Set File = fso.CreateTextFile(i&".bat",True)
File.Write batch
File.Close
Dim batchfile
batchfile = fso.GetAbsolutePathName(i&".bat")
WshShell.CurrentDirectory = strCurDir
WshShell.Run chr(34) & batchfile & Chr(34), 0, TRUE
fso.DeleteFile batchfile
I know the post is old but here is my solution, AGerman from dostips helped me code this script, its very useful.
#echo off &setlocal EnableExtensions DisableDelayedExpansion
:: Change the working directory to the directory of the batch file.
:: If the first passed argument was ~e~ (that is, the batch file was called from the VBScript)
:: then shift the parameters by one and continue at label :elevated
cd /d "%~dp0"&if "%~1"=="~e~" (shift&goto :elevated)
:: Assign the passed arguments to variable param.
set "param=%*"
:: NET SESSION fails if the batch code doesn't run with elevated permissions.
:: Assign variable __verb to "open" if the batch file runs elevated or to "runas" if it doesn't run elevated
>nul 2>&1 net session &&(set "__verb=open")||(set "__verb=runas")
:: Assign the name of the VBScript to variable vbs.
:: Assign the full name of the batch file to variable me.
:: Enable delayed variable expansion.
set "vbs=%temp%\uac.vbs"&set "me=%~f0"&setlocal enabledelayedexpansion
:: If arguments were passed, prepare them to be passed from within the VBScript by doubling the quotation marks.
if defined param set "param=!param:"=""!"
:: Write the VBScript. The ShellExecute method will run the batch file in a cmd.exe process where ~e~ will be passed as
:: first argument followed by the original arguments (saved in param). The UAC will be invoked if __verb was set to "runas".
:: Elsewise the UAC will not be invoked. For further information about the ShellExecute method see:
:: https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx
>"!vbs!" echo CreateObject("Shell.Application").ShellExecute "!comspec!", "/c """"!me!"" ~e~ !param!""", "", "%__verb%", 0
:: Run the VBScript in a cscript.exe process.
:: Delete the VBScript file.
:: Quit the batch execution.
cscript //nologo "!vbs!"&del "!vbs!"&goto :eof
:elevated
::~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:: Do your elevated stuff here...

>> Login screen : From Batch to VBscript and again to Batch <<

I am running a batch script and somewhere the user has to access a database.
At this moment, a window made in vbscript would prompt asking the user to type in the login and password. (OK, Cancel buttons)
If the credentials are correct after the OK, the batch would continue according to planA, otherwise the batch would do something else going to planB. If (Cancel), it would return to the batch and the menu above.
#echo off
:Ini
echo [1] Access database
echo [2] Main menu
echo:
set /p Quest= What do you prefer (1 / 2)?
if not '%Quest%'=='' set Quest=%Quest:~0,1%
if '%Quest%'=='1' goto VBS
if '%Quest%'=='2' goto BATCH
echo Invalid option, please try again
cls
goto Ini
:BATCH
echo Heading for main menu ...
goto Main
:VBS
cscript login.vbs
(...)
-- How to continue and make the vbs?
-- How to capture the user information, validate it and go back to the batch for the planA or planB ...
-- How to mask that password with ** ** ?
Help will be greatly appreciated !
Better switch to vbscript entirely (or since you seem new to vbscript another language more recent and powerfull while keeping it easy like Ruby). Everything you start from the batch can also be done in Vbscript, you can use prompt for the menu and inputbox for the password and if it has to be masked use a the browser as UI like the script from Rob Vanderwoude here http://www.robvanderwoude.com/vbstech_ui_password.php
Using this technique you can do all the UI/GUI in Internet Explorer and the logic in Vbscript.
If you decide to keep the batch approach, you can exit a vbs script with Wscript.Quit X, where x is the errorlevel you pass to windows when the script finishes, you can then trap that errorlevel in the batch. Alternative is to set or change an environment variable to do the trasfer of data, and last you can write data to textfiles easily in script and batch but the parsing of this in batch is more difficult.
I have found an intersting alternative as described below
http://www.computerhope.com/forum/index.php?topic=103686.0
VBSscript embeded in BATCH
#echo off
:wscript.echo InputBox("Enter your password","VBScript-Batch")
findstr "^:" "%~sf0" | findstr /i /v ":Label" >temp.vbs
for /f "delims=" %%N in ('cscript //nologo temp.vbs') do set pass=%%N
del temp.vbs
echo You entered %pass%
:Label1
echo continue from here
If %pass%=="ok" echo Valid Password ! & goto EOF
If %pass%=="ok" echo Invalid Password !! & goto EOF
:EOF
pause
As you see, if we eliminate the "& goto EOF" the script works well. It sends the VBS input "pass" to the batch and the batch echoes "continue from here", from where the rest of your code goes.
However, it is not working as it should. Any help to make this really work ?
Another alternative is ....
I have added in the existing VBSscript for "Internet Explorer version" the code :
VBS SCRIPT - named Password.vbs (see full script in the above link from Peter)
strPw = GetPassword( "Please, type your password:" )
WScript.Echo "Your password is: " & strPw
Sub Submit_OnClick
dim filesys, filetxt, FormContent
Set FormContent = document.getElementById("strPw")
Set filesys = CreateObject("Scripting.FileSystemObject")
Set filetxt = filesys.OpenTextFile("C:\\temp.txt", 8, True)
filetxt.WriteLine(FormContent.value)
filetxt.Close
End Sub
BATCH SCRIPT
#echo off
cscript Password.vbs
findstr /B /E /M %strPw% temp.txt
If %ERRORLEVEL% EQU 0 echo Password matched! & goto EOF
If not %ERRORLEVEL% EQU 0 echo Invalid Password !! & goto EOF
:eof
pause
The file temp.TXT should be sent to the c:\ with the information the user typed on the inputbox. The batch would read this input and compare to a set password and continue the coding...
How can I make this work?? the temp.TXT is not generated an so forth ...
BATCH and VBS gurus out there, any help to solve these problems is really welcomed !

Hiding a simple batch window

I've searched this and some pages came which weren't really useful or were too complicated (I am not a skilled batch file programmer!)! What I need is to run a batch file in hidden form (no console window). The batch file will not be called from external application or code. It will be clicked on by the client and then I want no console pages to be shown (only pages which are called by call command should be shown)! The batch file is exactly as follows:
#echo off
call setup.exe
IF EXIST "C:/caillog" goto tracking
IF NOT EXIST "C:/caillog" goto end
:tracking
call dotnet4.exe
call ClientService.msi
goto end
:end
I use VBScripts to open it hidden, like this:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("%batchfile%"), 0, True
for e.g the bat file I want to run is run.bat then I'll do like this
objShell.Run("run.bat"), 0, True
Instead of running the batch file run the vb file.
Write it in notepad and save it as *.vbs
If your Windows system supports powershell you can place this infront of "#echo off":
cmd /c powershell -Nop -NonI -Nologo -WindowStyle Hidden "Write-Host"
As others have said, use VBS.
Set WinScriptHost = CreateObject("WScript.Shell")
WinScriptHost.Run Chr(34) & "C:\FilePath" & Chr(34), 0
Set WinScriptHost = Nothing
This is what I use.

Resources