Batch Job to Write to VBS file - batch-file

I am trying to use a batch file to write this code to a VBS file but I cannot get a successful output. Can someone help?
This is what I am trying to write to Output.vbs
set w = CreateObject("WScript.Shell")
W.Run chr(34) & "C:\Program Files\Test\Test.bat" & chr(34), 0
set w= Nothing
I tried this:
>"C:\Program Files\Test\Output.vbs" (
echo set w = CreateObject("WScript.Shell")
echo W.Run chr(34) & "C:\Program Files\Test\Test.bat" & chr(34), 0
echo set w= Nothing
)
But the data I am getting in Output.vbs is only this:
set w = CreateObject("WScript.Shell"
It obviously doesn't like these ( and ) Is there a way around this? Not super skilled in CMD other than the basics. I assume I need to escape this somehow?
Any advice?
Thanks,

You need to escape the ampersands and nested closing parentheses, just like this:
#( Echo Set w = CreateObject("WScript.Shell"^)
Echo w.Run Chr(34^) ^& "C:\Program Files\Test\Test.bat" ^& Chr(34^), 0
Echo Set w = Nothing) 1> "C:\Program Files\Test\Output.vbs"

Related

How can I save addresses from batch file to text?

I want to save this code from batch file to txt but cant.
I write this code but this code not working, cant save the address
how can i save "some code" like this from batch file to txt.
i have many codes and need to save it at the right time from batch file to txt and not execute them just save as txt.
tnq
this code want to save:
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Program Files\Windows Task\WindowsTask.bat" & Chr(34), 0
Set WshShell = Nothing
this is my solution and not working:
#echo off
(echo Set WshShell = CreateObject^("WScript.Shell"^) )> sina.txt
(echo WshShell.Run chr^(34^) & "C:\Program Files\Windows Task\WindowsTask.bat" & Chr^(34^), 0) >> sina.txt
(echo Set WshShell = Nothing) >> sina.txt
pause
You have far less trouble with paranthesis and escaping if you put the redirection at the beginning of the line.
#echo off
> sina.txt echo Set WshShell = CreateObject("WScript.Shell")
>> sina.txt echo WshShell.Run chr(34) ^& "C:\Program Files\Windows Task\WindowsTask.bat" ^& Chr(34), 0
>> sina.txt echo Set WshShell = Nothing
pause
You need to double the %.
>> sina2.txt echo SET TodayYear=%%DATE:~10,4%%
The result in your file will be:
SET TodayYear=%DATE:~10,4%

Can you automatically check if there is a removable disk in batch?

I wanted to write a program in batch, which recognizes if you put in a USB stick and then automatically copies a folder. The copying was easy, but I'm struggling with recognizing the USB stick.
I've done this one but what if the USB stick has another letter and there's a hard drive on the letter "E". Also it checks only every 2 minutes. It would be nice if the program could instantly recognize the USB stick.
The code I have tried:
#echo off
goto search
:search
IF EXIST E: GOTO E
timeout /T 120 /nobreak
goto search
:F
xcopy /s F:\test\*.* C:\Users\sebas\Desktop\copied\*.*
exit
USB drives are removable disks, and can be found as follows:
Prompt>wmic logicaldisk get DeviceID, Description
Description DeviceID
Local Fixed Disk C:
Removable Disk D:
CD-ROM Disc E:
Removable Disk F:
You can get exactly the removable disks using this:
wmic logicaldisk get deviceid, description | find "Removable"
Using the link mark provided, this is How you would store the driveletter into a text file, then launch your batch program.
Include a bit of code in your Batch to recover the drive Letter and apply it to a Variable:
<StoreDriveLeterFilepath.txt (
Set /p Drive_Letter=
)
Adjust your XCOPY line to make use of the variable.
xcopy /s %Drive_Letter%\test\*.* C:\Users\sebas\Desktop\copied\*.*
The vbs code modified to store the drive into .txt and launch your Batch program.
Insert your Batch's Filepath where indicated
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set evtDevice = objWMIService.ExecNotificationQuery ("SELECT * FROM Win32_VolumeChangeEvent")
Wscript.Echo "Waiting for events ..."
Do
Set objReceivedEvent = evtDevice.NextEvent
'report an event
Wscript.Echo " Win32_Device Changed event occurred" & VBNewLine
If objReceivedEvent.EventType = 1 Then
Wscript.Echo "Type = Config Changed"
ElseIf objReceivedEvent.EventType = 2 Then
Wscript.Echo "Type = Device Arrived"
Set colItems = objWMIService.ExecQuery("Select * From Win32_Volume")
For Each objItem in colItems
If objitem.DriveType = 2 then
Wscript.Echo objItem.DriveType & " " & objItem.Name & " " & objItem.driveletter
Dim objFSO 'File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim objTS 'Text Stream Object
Const ForWriting = 2
Set objTS = objFSO.OpenTextFile("StoreDriveLeterFilepath.txt", ForWriting, True)
objTS.Write ("objItem.driveletter")
objTS.Close()
Set bjFSO = Nothing 'Destroy the object.
Set objTS = Nothing 'Destroy the object.
set WshShell=createobject("wscript.shell")
WshShell.run "Your Batch Filepath Here.bat", 1, true
End If
Next
ElseIf objReceivedEvent.EventType = 3 Then
Wscript.Echo "Type = Device Left"
ElseIf objReceivedEvent.EventType = 4 Then
Wscript.Echo "Type = Computer Docked"
End If
Loop

How to get particular code as output from a text file using batch?

I have a text file with a youtube link,
text file = url.txt , which consist,
https://www.youtube.com/watch?v=Videocode
my need is, by running a batch file how to get only that Videocode as output in another text file.
For example, if am running url.bat which need to convert "https://www.youtube.com/watch?v=Videocode" into "Videocode"
I hope you understand my need. Please gave me some solutions. Thanks in advance.
Taking the question as asked literally, a text file named url.txt containing a link in the format https://www.youtube.com/watch?v=Videocode, url.bat could just contain this:
#For /F "UseBackQ Tokens=2 Delims==&" %%A In ("C:\Users\niranja\Desktop\url.txt") Do #(Echo %%A)>"output.txt"
Change the path to your url.txt, C:\Users\niranja\Desktop\, to suit; or if it is in the same location as url.bat remove that path completely. The video ID you were looking for should be written to a file named output.txt in the same directory as url.bat.
Note: If question as written does not match your real intent, take a look at the link provided by Hackoo and start putting something together yourself!
Here is an idea with a vbscript using a Regex to extract the "Videocode"
Data = "https://www.youtube.com/watch?v=Videocode" & vbCrlf &_
"http://www.youtube.com/watch?v=iwGFalTRHDA" & vbCrlf &_
"http://www.youtube.com/watch?v=iwGFalTRHDA&feature=related" & vbCrlf &_
"http://youtu.be/iwGFalTRHDA" & vbCrlf &_
"http://youtu.be/n17B_uFF4cA" & vbCrlf &_
"http://www.youtube.com/embed/watch?feature=player_embedded&v=r5nB9u4jjy4" & vbCrlf &_
"http://www.youtube.com/watch?v=t-ZRX8984sc" & vbCrlf &_
"http://youtu.be/t-ZRX8984sc"
Data_Extracted = Extract(Data,"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?")
WScript.echo Data_Extracted
'************************************************
Function Extract(Data,Pattern)
Dim oRE,oMatches,Match,Line
set oRE = New RegExp
oRE.IgnoreCase = True
oRE.Global = True
oRE.Pattern = Pattern
set oMatches = oRE.Execute(Data)
If not isEmpty(oMatches) then
For Each Match in oMatches
Line = Line & Match.SubMatches(0) & vbcrlf
Next
Extract = Line
End if
End Function
'************************************************
EDIT : Using an hybrid code batch with a vbscript
#echo off
Title Extract Videocode from Youtube links
Set "Tmpvbs=%temp%\Tmpvbs.vbs"
Set "InputFile=URL.txt"
Set "OutPutFile=OutPutCode.txt"
Call :Extract "%InputFile%" "%OutPutFile%"
Start "" "%OutPutFile%" & exit
::****************************************************
:Extract <InputData> <OutPutData>
(
echo Data = WScript.StdIn.ReadAll
echo Data = Extract(Data,"http(?:s?):\/\/(?:www\.)?youtu(?:be\.com\/watch\?v=|\.be\/^)([\w\-\_]*)(&(amp;)?‌​[\w\?‌​=]*)?"^)
echo WScript.StdOut.WriteLine Data
echo '************************************************
echo Function Extract(Data,Pattern^)
echo Dim oRE,oMatches,Match,Line
echo set oRE = New RegExp
echo oRE.IgnoreCase = True
echo oRE.Global = True
echo oRE.Pattern = Pattern
echo set oMatches = oRE.Execute(Data^)
echo If not isEmpty(oMatches^) then
echo For Each Match in oMatches
echo Line = Line ^& Match.SubMatches(0^) ^& vbcrlf
echo Next
echo Extract = Line
echo End if
echo End Function
echo '************************************************
)>"%Tmpvbs%"
cscript /nologo "%Tmpvbs%" < "%~1" > "%~2"
If Exist "%Tmpvbs%" Del "%Tmpvbs%"
exit /b
::**********************************************************************************

Passing variables from VBs to Batch File

I'm just struggling with this seemingly simple code:
a = objNode.Text
dim WshShell
set WshShell=Wscript.Createobject("Wscript.shell")
WshShell.Run chr(34) & "C:\Users\c1921\Ayla_Data\ccode.bat " & Chr(34) & a & filename 'this line here does not work right.
Set WshShell = Nothing
The code does almost what I want it to. This is the batch file code:
#echo off
echo test passed variables:
echo %1
echo %2
pause
But echo %1 returns both values and echo %2 returns echo off:
219270AC000N000009132
ECHO OFF
I don't understand what I'm doing wrong. I've tried adding extra quotes in this line:
WshShell.Run ""C:\Users\c1921\Ayla_Data\ccode.bat "" a & filename 'variation 1
WshShell.Run """C:\Users\c1921\Ayla_Data\ccode.bat """ a & filename 'variation 2
WshShell.Run chr(34) & "C:\Users\c1921\Ayla_Data\ccode.bat " & Chr(34) & a + filename 'variation 3
I don't understand what I'm missing here?
Any help in the right direction would be great. If there's any helpful documentation on using vbs and batch that would be great too.
DM
... & a & filename
is the problem. You just concatenate the arguments, instead of separating them with a space. That's why the batch file only sees the first argument which contains both at once. echo %2 will then yield ECHO is off. because %2 is empty.
... & a & " " & filename
should work. For some values of work, I guess. If either a or filename contains spaces it'll probably blow up. You can add quotes around them to prevent that:
... & Chr(34) & a & Chr(34) & " " & Chr(34) & filename & Chr(34)
Then %1 and %2 in the batch file will include the quotes, though. To remove them there you can use %~1 and %~2 respectively.

windows ".lnk" shortcuts and batches don't mix

I have a batch file which is used by dragging a folder containing .mp3s into the batch.
#echo off
cd %~dp0
setlocal enabledelayedexpansion enableextensions
set FLDR="%1"
if not defined FLDR ( echo Drag a folder to the batch to play its contents.
pause
goto:EOF )
for %%x in (%FLDR%\*.mp3) do set "MP3=!MP3! "%%x""
mp3player %MP3%
pause
It works fine with actual folders, but when dragging shortcuts, the variable %FLDR% ends up as "c:\link location\folder.lnk" instead of the actual folder location.
I have no idea how to get around this.
Here is a way to get the target using a little hybrid VBS/Batch file function.
#echo off
setlocal
Call :GetTarget "%~1" tgt
echo %tgt%
pause
exit /b
:GetTarget
#echo off & setlocal
set gt=%temp%\_.vbs
echo set WshShell = WScript.CreateObject("WScript.Shell")>%gt%
echo set Lnk = WshShell.CreateShortcut(WScript.Arguments.Unnamed(0))>>%gt%
echo wscript.Echo Lnk.TargetPath>>%gt%
set script=cscript //nologo %gt%
For /f "delims=" %%a in ( '%script% "%~1"' ) do set target=%%a
del %gt%
endlocal & set %~2=%target%
exit /b
HYBRID SCRIPT! No silly little temporary files.
::'<SUB>#echo off
::'<SUB>set shortcut=%~1
::'<SUB>if not defined shortcut goto 'usage
::'<SUB>if not %shortcut:~-4%==.lnk (if not %shortcut:~-4%==.url (set errorlevel=1
::'<SUB>goto 'usage ))
::'<SUB>if not exist %shortcut% (echo Error: Nonexistent shortcut
::'<SUB>set errorlevel=1
::'<SUB>goto:EOF )
::'<SUB>setlocal
::'<SUB>for /f "delims=" %%T in ('cscript //nologo //e:vbs %~nx0 "%shortcut%"') do set thing=%%T
::'<SUB>endlocal & set shortcut=%thing%
::'<SUB>goto:EOF
:'usage
::'<SUB>echo command-line shortcut redirect utility
::'<SUB>echo Usage: shortcut [file.lnk ^| file.url]
::'<SUB>echo The resulting link will be output to the %%shortcut%% variable.
::'<SUB>goto:EOF
set WshShell = WScript.CreateObject("WScript.Shell")
set Lnk = WshShell.CreateShortcut(WScript.Arguments.Unnamed(0))
wscript.Echo Lnk.TargetPath
Where <SUB> indicates the substitute character.
UPDATE: I found a much fully vbscript solution over at Wayne's World of IT, and modified it slightly to suit my needs:
If WScript.Arguments.UnNamed.Count = 1 Then
strShortcut = WScript.Arguments.UnNamed(0)
Else
WScript.Echo "Please supply the name of an lnk file or directory to read, eg c:\test.lnk or c:\shortcuts"
WScript.Quit(1)
End If
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strShortCut) Then
Set objFolder = objFSO.getFolder(strShortcut)
For Each objfile in objFolder.Files
If objfile.type = "Shortcut" Then
Call Readshortcut(objFile.Path, strProperties)
dtmCreationDate = objFile.DateCreated
WScript.Echo dtmCreationDate & "," & strProperties
End If
Next
ElseIf objFSO.FileExists(strShortCut) Then
Call Readshortcut(strShortcut, strProperties)
WScript.Echo strProperties
Else
WScript.Echo "Error: Could not read '" & strShortcut & "'"
WScript.Quit(2)
End If
Set objFSO = Nothing
Function Readshortcut(ByRef strShortcut, ByRef strProperties)
set objWshShell = WScript.CreateObject("WScript.Shell")
set objShellLink = objWshShell.CreateShortcut(strShortcut)
strProperties = objShellLink.TargetPath & " " & objShellLink.Arguments
Set objShellLink = Nothing
Set objWshshell = Nothing
End Function

Resources