Exit batch script - batch-file

I have batch script,I saved res.bat and run,but it is not Exit when finish run.Help me!!!
echo Set objShell = CreateObject( "WScript.Shell" ) > %TEMP%\sp.vbs
echo Set objSystemEnv = objShell.Environment( "SYSTEM" ) >> %TEMP%\sp.vbs
echo objSystemEnv("Path") = objSystemEnv("Path") ^& ";ABCAA" >> %TEMP%\sp.vbs
cscript.exe /nologo %TEMP%\sp.vbs
del %TEMP%\sp.vbs
cls

Try putting an #exit command at the end of the script.
Or you can try this script:
Dim objShell : Set objShell = CreateObject("WScript.Shell")
Dim objSysEnv : Set objSysEnv = objShell.Environment("SYSTEM")
objSysEnv("PATH") = objSysEnv("PATH") & ";ABCAA"
and save it as vbs. It will run with no window at all. Tested on my PC. I had to clean my path variable since I will not be using it :). It's not bat, but it,s working.

It the end of the code #exit WILL NOT WORK! Try doing just exit or maybe close or stop.

Related

How can i run the window of the started program minimized

i want to run a .wav-file. This is with
start "" SoundFile.wav
totally practical. But how can i run the window of the standard-windows-soundplayer minimized? So that nothing of my view changes?
start "" SoundFile.wav /MIN
start "" SoundFile.wav /min
start "" SoundFile.wav -MIN
start "" SoundFile.wav -min
didn't work sadly.
Can you help me?
Greets.
Sorry but i am not familiar with stackoverflow, so i can't make it that understandable, but i hope that this is enough.
In a simple way, you could just use a VBS like this:
s = createobject("WScript.Shell")
s.run "music.mp3", 2
Or create an automatic and CLI program to do this:
runmusic.bat
#echo off
set music=%1
set music=%music:"=%
if ":" neq "%music:~1,1%" set music=%cd%\%music%
if "%music:~-4%" neq ".mp3" set music=%music%.mp3
set katorn=%random%
echo >>"%temp%\%katorn%.vbs" set s = createobject("WScript.Shell")
echo >>"%temp%\%katorn%.vbs" s.run "%music%", 2
cscript "%temp%\%katorn%.vbs"
:: Uncomment the next line to autodelete the vbs file.
:: del /q /f "%temp%\%katorn%.vbs"
Usage:
runmusic (name or full path with quotation marks)
In a "professional way" you could do a shortcut file that starts the file minimized.
It could be useful if you needs the musics to have the "artist logo" or something like that, also if you don't want to use an CMD all the time...
Delete all comments to execute.
Set WshShell = CreateObject ("Wscript.Shell")
strDesktop = "X:\Shortcutlocation\yoo"
Set Shortcut = WshShell.CreateShortcut(strDesktop + "\MusicNameMaybe.lnk")
Shortcut.WindowStyle = "7"
Shortcut.IconLocation = "X:\IconPath\youricon.ico" // You can delete this and the file will be the same ever and forever.
Shortcut.TargetPath = "X:\yourpath\music.mp3"
Shortcut.Save
And you don't have to keep the shortcuts on the desktop if you don't want to, you don't even have to keep them fixed. Example:
runmusic.bat
#echo off
set music=%1
set music=%music:"=%
if ":" neq "%music:~1,1%" set music=%cd%\%music%
set music=%music%.mp3
set katorn=%random%
echo >>"%temp%\%katorn%.vbs" Set WshShell = CreateObject ("Wscript.Shell")
echo >>"%temp%\%katorn%.vbs" strDesktop = "%temp%"
echo >>"%temp%\%katorn%.vbs" Set Shortcut = WshShell.CreateShortcut(strDesktop + "\%katorn%.lnk")
echo >>"%temp%\%katorn%.vbs" Shortcut.WindowStyle = "7"
echo >>"%temp%\%katorn%.vbs" Shortcut.TargetPath = "%music%"
echo >>"%temp%\%katorn%.vbs" Shortcut.Save
cscript "%temp%\%katorn%.vbs"
:: Uncomment the next two lines to delete the temporary files.
:: del /q /f "%temp%\%katorn%.vbs"
:: del /q /f "%temp%\%katorn%.lnk"
echo Enjoy!
Usage:
runmusic (name or full path with quotation marks)
Now that you understand, you can even leave a folder with the songs and the other with just the customized shortcuts, which can come in handy.
Hope this helps,
K.

Execute specific vbs file from batch file

Batch content:
echo Set wshShell =wscript.CreateObject("WScript.Shell")>"C:\Users\Riccardo\Desktop\prova.vbs"
<nul set /p =wshshell.sendkeys ^"^<nul set ^/p ^=>>"C:\Users\Riccardo\Desktop\prova.vbs"
Type "C:\Users\Riccardo\Desktop\prova.txt">>"C:\Users\Riccardo\Desktop\prova.vbs"
echo {bs}^>^"^"C:\Users\Riccardo\Desktop\prova.txt^"^"{enter}^">>"C:\Users\Riccardo\Desktop\prova.vbs"
wscript "C:\Users\Riccardo\Desktop\prova.vbs"
The vbs generated is:
Set wshShell =wscript.CreateObject("WScript.Shell")
wshshell.sendkeys "<nul set /p =La#{bs}>""C:\Users\Riccardo\Desktop\prova.txt""{enter}"
The prova.txt contains:
La#
After execute this line from new command prompt session:
wscript "C:\Users\Riccardo\Desktop\prova.vbs"
The prova.txt becomes
La
But if execute the same line as above from batch:
wscript "C:\Users\Riccardo\Desktop\prova.vbs"
nothing happens!
How can I fix the problem?
Try to call the script like so:
C:\Users\Riccardo\Desktop\prova.vbs
If that doesn't work, change directory to your desktop, and call the vbs:
cd C:\Users\Riccardo\Desktop\
prova.vbs
That should work in a batch file.
I am solved the my problem. The "Prova.bat" code is:
echo Set wshShell =wscript.CreateObject("WScript.Shell")>prova.vbs
echo wshShell.Run "cmd">>prova.vbs
echo WScript.Sleep 250>>prova.vbs
<nul set /p =wshShell.sendkeys ^"^<nul set ^/p ^=>>prova.vbs
Type prova.txt>>prova.vbs
<nul set /p ={bs}^>prova.txt{enter}exit{enter}^">>prova.vbs
wscript prova.vbs
DEL /q prova.vbs 2> NUL
The "Prova.vbs" generated and deleted is:
Set wshShell =wscript.CreateObject("WScript.Shell")
wshShell.Run "cmd"
WScript.Sleep 250
wshShell.sendkeys "<nul set /p =La#8{bs}>prova.txt{enter}exit{enter}"
The "Prova.txt" before:
La#8
The "Prova.txt" now:
La#
I am found the way of insert backspace character in a txt file using bat+vbs file! ;-) I hope that such a solution can be of help to someone else.

.vbs(5, 1) Microsoft VBScript runtime error: Subscript out of range Error:800A0009

This is my first question on here, because, although I have searched at least 15 different other posts for the answer to my issue, none have the answer. Please help!
QUESTION: How do I fix Error:800A0009?
DETAILS: I am creating a small program that gathers all local computers and sends them all an audio file to be played. Also, I need to know how to force send, if anyone knows. Lastly, I first run "Get Computers.bat".
My Code:
~~~~~~VBS FILE(Remote Speak.vbs)~~~~~~~~~~~~~~~~~~~
(Obtains variable transferred which contains network name of a computer, and sends it a file to be play using SAPI)
'get ip
Option Explicit
Dim args, strOut
set args = Wscript.arguments
strOut= args(0)
IP = strOut
'get MSG
MSG = InputBox("Type what you want the PC to say:", "Remote Voice Send By X BiLe", "")
If MSG = "" Then WScript.quit: Else
'vbs command to send
A = "on error resume next" & VBCRLF & _
"CreateObject(""SAPI.SpVoice"").speak " & """" & MSG & """" & VBCRLF & _
"CreateObject(""Scripting.FileSystemObject"").DeleteFile (""C:\Voice1.vbs"")"
' Create the vbs on remote C$
CreateObject("Scripting.FileSystemObject").OpenTextFile("\\" & ip & "\C$\Voice1.vbs",2,True).Write A
' Run the VBS through Wscript on remote machine via WMI Object Win32_Process
B = GetObject("winmgmts:\\" & IP & "\root\cimv2:Win32_Process").Create("C:\windows\system32\wscript.exe ""C:\Voice1.vbs""", null, null, intProcessID)
~~~BATCH PRIMARY (Get Computers.bat)~~~~~~~~~~~
(Gathers computer names and assign each one, using net view, filtering the "\" to Computer%num%. Also, :tempcall is just an error handler.)
#echo off
cls
set num=1
echo #echo off > Computers.bat
if "%1"=="loop" (
for /f "delims=\ tokens=*" %%a in ('net view ^| findstr /r "^\\\\"') do (
set comp=%%a
call :number
if exist %%f exit
)
goto :eof
)
cmd /v:on /q /d /c "%0 loop"
:tempcall
call temp.bat
echo.
echo.
echo.
echo You have %num%computers on your network!
pause>nul
del /q temp.bat
start Computers.bat
exit
:number
if %comp% == "" (
goto :tempcall
) else (
echo set Computer%num%=%comp% >> Computers.bat
echo cscript "Remote Speak.vbs" %1 >> Computers.bat
echo call "Remote Speak.vbs" >> Computers.bat
echo set num=%num% > temp.bat
echo Computer%num%: %comp%
set /a num=%num% + 1
)
BATCH SECONDARY (Computers.bat)
(The computers I made up off the top of my head, but they are generally in that format.)
#echo off
set Computer1=040227-CYCVN1
cscript "Remote Speak.vbs" //NoLogo > log.txt
set Computer1=051448-YZVN2
cscript "Remote Speak.vbs" //NoLogo > log.txt
pause>nul
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~END DETAILS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1.) Temp.bat is literally just temporary, it's deleted, as you can see, almost immediately after it's created, it simply holds the value of %num% after it breaks out of the loop, because it didn't show "You have %num%computers on your network!" correctly.
2.) Don't worry too much about the VBScript file except for the top lines:
Option Explicit
Dim args, strOut
set args = Wscript.arguments
strOut= args(0)
IP = strOut
3.) My main issue is that I am trying to find a safe way to have "Computers.bat" call the "Remote Speak.vbs" file and set it's batch variables to be the exact same names to refer to the individual computers, in VBScript variable format.
The error raises because you are not passing any argument to the vbs file, and it is not passed because when you generate computers.bat you are using %1 (the first argument to the :number subroutine) as a parameter, but in call :number there is not any parameter.
Also, the incrementing computer number is not shown in computers.bat because delayedexpansion is not active. When execution reaches a line or block (the code inside parenthesis), the parser replaces variable reads with the value in the variable and then starts to execute it. As the value of the variable changes inside the block, but there is no variable read, only the value of the variable before starting to execute, changes are not seen. You need to setlocal enabledelayedexpansion to enable it and, where needed, change %var% to !var! to indicate the parser that the variable read needs to be delayed, not replaced at initial parse time.
And anyway, your code does not use it. And what is if exist %%f? And why the loop?
For your third question, the Environment property of the WshShell objects lets you read the required variables
Dim env
Set oEnvironment = WScript.CreateObject("WScript.Shell").Environment("PROCESS")
WScript.Echo oEnvironment("Computer1")
This is a fast cleanup of your code. From your question it seems this is only the starting point. Adapt as needed.
RemoteSpeak.vbs
Option Explicit
If WScript.Arguments.Count < 1 Then
WScript.Quit
End If
'get ip
Dim IP
IP = WScript.Arguments.Item(0)
'get MSG
Dim MSG
MSG = InputBox("Type what you want the PC to say:", "Remote Voice Send By X BiLe", "")
If MSG = "" Then
WScript.Quit
End If
Dim A
A = "on error resume next" & VBCRLF & _
"CreateObject(""SAPI.SpVoice"").speak " & """" & MSG & """" & VBCRLF & _
"CreateObject(""Scripting.FileSystemObject"").DeleteFile(WScript.ScriptFullName)"
' Create the vbs on remote C$
CreateObject("Scripting.FileSystemObject").OpenTextFile("\\" & IP & "\C$\Voice1.vbs",2,True).Write A
' Run the VBS through Wscript on remote machine via WMI Object Win32_Process
Dim B
B=GetObject("winmgmts:\\" & IP & "\root\cimv2:Win32_Process").Create("C:\windows\system32\wscript.exe ""C:\Voice1.vbs""", null, null, intProcessID)
getComputers.bat
#echo off
setlocal enableextensions enabledelayedexpansion
cls
set "num=0"
( echo #echo off
for /f "tokens=* delims=\" %%a in ('net view ^| findstr /r /c:"^\\\\"') do (
set /a "num+=1"
echo set "Computer!num!=%%a"
echo cscript "RemoteSpeak.vbs" %%a
)
) > computers.bat
echo You have %num% computers in your network
pause > nul
start Computers.bat
endlocal
exit /b
Dim env
Set oEnvironment = WScript.CreateObject("WScript.Shell").Environment("PROCESS")
WScript.Echo oEnvironment("Computer1")

Use Batch File Processing To Remove Last Character

I have a process where an incoming file is csv and has trailing commas after the last entry.
I need to process this and send it out sans that final comma as it causes a verification error with the phantom "empty column"
Currently I've got this piece of code to write each line into a new file:
for /f "tokens=* delims=" %%x in (file.csv) do echo %%i >> test.txt
And I've been trying to use something like echo %string:~0,-1% to remove the trailing comma in conjunction but I'm not having much luck. I don't think %%i can be used the same as a string would be referenced with the above. I've tried writing %%i into a string but seems I've got that syntax wrong too.
[edit]
I do run the file through a vbs script to replace the commas with pipes (, = |) so if there's an easier way to do it as part of that process, in my searching of stackoverflow to try and resolve this prior to asking I found this line which I thought may help:
strNewText = strNewText.Substring(0,strNewText.Length-1)
strNewText being the variable holding the updated data, doesn't work though, now the find and replace text section doesn't actually run when I add that in:
rem CREATE Find And Replace Text VBS SCRIPT
echo Const ForReading = 1 > "%tmp%\fart.vbs"
echo Const ForWriting = 2 >> "%tmp%\fart.vbs"
echo strFileName = Wscript.Arguments(0) >> "%tmp%\fart.vbs"
echo strOldText = Wscript.Arguments(1) >> "%tmp%\fart.vbs"
echo strNewText = Wscript.Arguments(2) >> "%tmp%\fart.vbs"
echo Set objFSO = CreateObject("Scripting.FileSystemObject") >> "%tmp%\fart.vbs"
echo Set objFile = objFSO.OpenTextFile(strFileName, ForReading) >> "%tmp%\fart.vbs"
echo strText = objFile.ReadAll >> "%tmp%\fart.vbs"
echo objFile.Close >> "%tmp%\fart.vbs"
echo strNewText = Replace(strText, strOldText, strNewText) >> "%tmp%\fart.vbs"
echo strNewText = strNewText.Substring(0,strNewText.Length-1) >> "%tmp%\fart.vbs"
echo Set objFile = objFSO.OpenTextFile(strFileName, ForWriting) >> "%tmp%\fart.vbs"
echo objFile.WriteLine strNewText >> "%tmp%\fart.vbs"
echo objFile.Close >> "%tmp%\fart.vbs"
(all the echo's are because I generate the vbs during the batch runtime, I tend to find things easier when everything's done in the one file, this vbs file is then deleted later in the process).
#if (#This==#IsBatch) #then
#echo off
rem **** batch zone *********************************************************
type inputfile.csv | cscript //nologo //e:javascript "%~f0" > outputfile.csv
exit /b
#end
// **** Javascript zone *****************************************************
while (!WScript.StdIn.AtEndOfStream) WScript.StdOut.WriteLine(WScript.StdIn.ReadLine().replace(/,[\s,]+$/,''));
This is an hybrid batch/javascript file. Save as batch file, execute and the inputfile.csv file will be piped into cscript.exe that will execute the javascript code included in the same batch file, iterating over the piped data and deleting all commas and final spaces from last comma to end of line. Output from pipe is sent to outputfile.csv
EDITED - As stated in comments, maybe i missunderstood the question, and it is not necessary to remove commaS at the end of the lines, but only the final comma. In this case, the replace expression should be
... .replace(/,$/,''));
Probably the simplest solution for your problem would be sed for Windows:
C:\>sed "s/,$//" <in.csv >out.csv
You could also write a simple VBScript that does the same thing:
Set re = New RegExp
re.Pattern = ",$"
Do Until WScript.StdIn.AtEndOfStream
WScript.Echo re.Replace(WScript.StdIn.ReadLine, "")
Loop
Usage:
C:\>cscript //NoLogo script.vbs <in.csv >out.csv
PowerShell would be an even better option:
PS C:\> (Get-Content 'in.csv') -replace ',$' | Out-File 'out.csv'
I would not recommend using batch for this.
I'm not sure this will work, but since you only want the code to apply for the last line, I've tried implementing the code differently from your average for loop.
#echo off
setlocal enabledelayedexpansion
set previous=
set current=
ren file.csv file.tmp
3<file.tmp (
:loop
set previous=!current!
set /p current=<&3
if "!current!" == "!previous!" (
Echo !current:~0,-1! >> file.csv
) Else (
Echo !current! >> file.csv
goto :loop
)
)
type file.csv
Echo. &Echo Only delete if file.csv is not corrupt
del /p file.tmp
Endlocal
And that should about do what you want.
Mona.

Error in running a batch file from VB Script

VB scripting is completely alien to me but today landed in a situation to write a small one. I need Admin rights to run my .bat file. So I am trying to elevate to Admin rights if not have them. With the help of SO and Google I reached upto:
Function Length()
Set WshShell = WScript.CreateObject("WScript.Shell")
If WScript.Arguments.length = 0 Then
Set ObjShell = CreateObject("Shell.Application")
ObjShell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """" & " RunAsAdministrator", , "runas", 1
Else
Dim shell
set shell=createobject("wscript.shell")
shell.run "ExtractFiles.bat"
End If
End Function
Length
Here, this .vbs and ExtractFiles.bat are saved in same folder. I opened 2 command prompts. One in Admin mode and other normal. When running this script thorugh command prompt in Admin mode, I am getting success. But in normal mode, first I get a window to switch to Admin mode and I press Yes on it. Then I get below error:
Can anyone point me to correct code. I am getting error in line shell.run "ExtractFiles.bat". Please help!
As I have also mentioned the requirement, a different approach is also welcome. In this problem, I am not sure how I am able to run the bat file in admin mode and failing in normal mode.
Add the Admin VBS code into your bat file. Here is my routine for the job.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:Admin <Return> [Needed] [Success]
:: Check for Administrator privileges and request privileges if Needed 'true'.
:::: Usage: call :Admin xReturn true
:: Return success value, if user is Admin. Default `true` if Success not set.
setlocal
set "xVBUAC=%Temp%\AdminUAC.vbs"
set "xSuccess=true"
set "xAdmin=false"
if not "%~3"=="" set "xSuccess=%~3"
:: Check for Access
::net session >nul 2>&1
>nul 2>&1 "%SystemRoot%\system32\cacls.exe" "%SystemRoot%\system32\config\system"
if %ErrorLevel% EQU 0 set "xAdmin=%xSuccess%"
:: Execute UAC
if /i not "%xAdmin%"=="%xSuccess%" if not "%~2"=="" if /i "%~2"=="true" (
echo Set UAC = CreateObject^("Shell.Application"^) > "%xVBUAC%"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%xVBUAC%"
if exist "%xVBUAC%" (
"%xVBUAC%"
rem if %ErrorLevel% EQU 5 echo Access Denied. Launching UAC.
del "%xVBUAC%"
)
)
endlocal & if not "%~1"=="" set "%~1=%xAdmin%"
goto :eof
How to Use it
:: Example Admin check
#echo off
setlocal EnableExtensions
call :Admin xReturn true 1
if not "%xReturn%"=="1" goto End
:: Do my .bat stuff here.
goto End
:: TODO Place the admin function here.
:End
Depending on how you launch the VBScript the directory in which the scripts reside isn't necessarily the working directory. Try this:
Set fso = CreateObject("Scripting.FileSystemObject")
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
shell.run "%COMSPEC% /c """ & fso.BuildPath(scriptDir, "ExtractFiles.bat") & """"
What you enter in the command prompt? Is it...
InstallACS.vbs ExtractFiles.bat
Your script works just fine on XP x64 (if that important) never mind how I'll run it - from the sell or from the console, and also work with and without argument.

Resources