Batch commands and VB script commands in one file - batch-file

I have created one batch file through which I am trying to create one .vbs file and place some command into that. But I am not able to transfer my all the command to the .vbs file.
#echo off
echo:
set /a i=1
:Loop
if %i% GTR 0 (
rem create temp vbs file
echo Dim IPAddress > temp.vbs
echo IPAddress="192.168.1.109" >> temp.vbs
echo SET WshShell = WScript.CreateObject("WScript.Shell"^) >> temp.vbs
echo WshShell.run("telnet.exe " &IPAddress) >> temp.vbs
echo WScript.Sleep 3000 >> temp.vbs
echo WshShell.SendKeys"qwert" >> temp.vbs
echo WshShell.SendKeys("{Enter}") >> temp.vbs
echo WScript.Sleep 3000 >> temp.vbs
echo WshShell.SendKeys"asdf123" >> temp.vbs
echo WshShell.SendKeys("{Enter}") >> temp.vbs
echo WScript.Sleep 1000 >> temp.vbs
echo ' Reboot Device >> temp.vbs
echo ' WshShell.SendKeys"reboot" >> temp.vbs
echo ' WshShell.SendKeys("{Enter}") >> temp.vbs
echo ' WScript.Sleep 1000 >> temp.vbs
echo strPath = WshShell.CurrentDirectory >> temp.vbs
echo ' Close telnet session >> temp.vbs
echo WshShell.Run "taskkill /im telnet.exe", , True >> temp.vbs
rem wscript C:\Users\guest\Desktop\temp.vbs
echo Reboot Count %i%
echo:
set /a i+=1
Timeout /t 90 >nul
GOTO Loop
) ELSE (
echo Out of if loop
)
Following is the Actual output of the temp.vbs file
WshShell.run("telnet.exe "
WScript.Sleep 3000
WshShell.SendKeys"qwert"
WshShell.SendKeys("{Enter}")
WScript.Sleep 3000
WshShell.SendKeys"asdf123"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1000
' Reboot Device
' WshShell.SendKeys"reboot"
' WshShell.SendKeys("{Enter}")
' WScript.Sleep 1000
strPath = WshShell.CurrentDirectory
' Close telnet session
WshShell.Run "taskkill /im telnet.exe", , True
Expected output of temp.vbs file
Dim IPAddress
IPAddress="192.168.1.109"
SET WshShell = WScript.CreateObject("WScript.Shell"^)
WshShell.run("telnet.exe " &IPAddress)
WScript.Sleep 3000
WshShell.SendKeys"qwert"
WshShell.SendKeys("{Enter}")
WScript.Sleep 3000
WshShell.SendKeys"asdf123"
WshShell.SendKeys("{Enter}")
WScript.Sleep 1000
' Reboot Device
' WshShell.SendKeys"reboot"
' WshShell.SendKeys("{Enter}")
' WScript.Sleep 1000
strPath = WshShell.CurrentDirectory
' Close telnet session
WshShell.Run "taskkill /im telnet.exe", , True
Kindly help me on this to achieve this scenario.
Thank your very much in advance.

You can create a .vbs script with commands you walt to run in the same folder and hidden it. Next you can run it from batch file.

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%

Batch exe to shortcut

Currently, I am attempting to create a shortcut for a program, I was able to do so shown in the code below.
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%HOMEDRIVE%%HOMEPATH%\Desktop\Unturned Dedicated Server\Unturned - Server.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "C:\Program Files (x86)\Steam\steamapps\common\Unturned\Unturned.exe" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs
The issue is I need the target path to be, "C:\Program Files (x86)\Steam\steamapps\common\Unturned\Unturned.exe" -batchmode -nographics +secureserver/ahhh
How would I go about doing so?
To do this as a batch-file, which creates a vbscript, runs it, then deletes it, I'd suggest that you do it like this:
#( Echo Set WshShell = WScript.CreateObject("WScript.Shell"^)
Echo strDesktop = WshShell.SpecialFolders("Desktop"^)
Echo str32bitPF = WshShell.ExpandEnvironmentStrings("%%ProgramFiles(x86)%%"^)
Echo Set oFSO = CreateObject("Scripting.FileSystemObject"^)
Echo If Not (oFSO.FolderExists(strDesktop + "\Unturned Dedicated Server"^)^) Then
Echo oFSO.CreateFolder(strDesktop + "\Unturned Dedicated Server"^)
Echo End If
Echo Set oShellLink = WshShell.CreateShortcut(strDesktop + "\Unturned Dedicated Server\Unturned - Server.lnk"^)
Echo oShellLink.Arguments = "-batchmode -nographics +secureserver/ahhh"
Echo oShellLink.TargetPath = str32bitPF + "\Steam\steamapps\common\Unturned\Unturned.exe"
Echo oShellLink.WindowStyle = 1
Echo oShellLink.Hotkey = "CTRL+SHIFT+U"
Echo oShellLink.Description = "Launch Unturned"
Echo oShellLink.WorkingDirectory = strDesktop + "\Unturned Dedicated Server"
Echo oShellLink.Save) > "CreateShortcut.vbs"
#%__AppDir__%cscript.exe /NoLogo "CreateShortcut.vbs"
#Del "CreateShortcut.vbs"
However, you can also do it directly from your batch-file without writing to a file too.
<!-- :
#%__AppDir__%cscript.exe /NoLogo "%~f0?.wsf"
#GoTo :EOF
-->
<Job><Script Language="VBScript">
Set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
str32bitPF = WshShell.ExpandEnvironmentStrings("%ProgramFiles(x86)%")
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not (oFSO.FolderExists(strDesktop + "\Unturned Dedicated Server")) Then
oFSO.CreateFolder(strDesktop + "\Unturned Dedicated Server")
End If
Set oShellLink = WshShell.CreateShortcut(strDesktop + "\Unturned Dedicated Server\Unturned - Server.lnk")
oShellLink.Arguments = "-batchmode -nographics +secureserver/ahhh"
oShellLink.TargetPath = str32bitPF + "\Steam\steamapps\common\Unturned\Unturned.exe"
oShellLink.WindowStyle = 1
oShellLink.Hotkey = "CTRL+SHIFT+U"
oShellLink.Description = "Launch Unturned"
oShellLink.WorkingDirectory = strDesktop + "\Unturned Dedicated Server"
oShellLink.Save
</Script></Job>
If you wish to add your own batch-file code to this version it must be inserted just above the #GoTo :EOF line.
You should add another line where to put the arguments to be passed to your .exe target :
#echo off
Title Batch exe to shortcut
Set "VBS_Shortcut=%temp%\%~n0.vbs"
Set "ShortcutName=Unturned - Server"
Set "TargetPath=C:\Program Files (x86)\Steam\steamapps\common\Unturned\Unturned.exe"
Set "Arguments=-batchmode -nographics +secureserver/ahhh"
Call :Create_Shortcut "%ShortcutName%" "%TargetPath%" "%Arguments%"
Exit
REM ----------------------------------------------------------------------------------------------------
:Create_Shortcut
> "%VBS_Shortcut%" (
echo Call Create_Shortcut("%~1","%~2","%~3"^)
echo Sub Create_Shortcut(ShortcutName,TargetPath,Arguments^)
echo Dim objShell,DesktopPath,objShortCut
echo Set objShell = CreateObject("WScript.Shell"^)
echo DesktopPath = objShell.SpecialFolders("Desktop"^)
echo Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& ShortcutName ^& ".lnk"^)
echo objShortCut.TargetPath = chr(34^) ^& TargetPath ^& chr(34^)
echo objShortCut.Arguments = Arguments
echo objShortCut.Save
echo End Sub
)
cscript //nologo "%VBS_Shortcut%" "%~1" "%~2" "%~3"
If Exist "%VBS_Shortcut%" Del "%VBS_Shortcut%"
Exit /B
REM ----------------------------------------------------------------------------------------------------

using variables from VBScript in batch

I want to pass variables from VBScript to batch but it wouldn't work.
My VBScript:
Dim shell
Set shell = CreateObject("WScript.Shell")
strnaam = InputBox ("naam")
and my batch:
#echo off
cls
echo %strnaam%
pause
I want the variable strnaam from my VBScript to my batch.
The most obvious way would be to run the vbscript as a For /F command and save its returned output as a variable:
#Echo Off
:NaamBox
Set "naam="
(Echo WScript.Echo InputBox("Naam:"^))>"%TEMP%\naam.vbs"
For /F Delims^=^ EOL^= %%A In ('CScript //NoLogo "%TEMP%\naam.vbs"')Do Set "naam=%%A"
If Not Defined naam GoTo NaamBox
Del "%TEMP%\naam.vbs"
Echo Uw naam is %naam%
Pause
If you don't like the idea of writing, running, then deleting the file, you could also embed your VBScript within the batch file:
<!-- :
#Echo Off
Echo Typ gelieve uw naam in de popup doos en OK te selecteren
For /F Delims^=^ EOL^= %%A In ('CScript //NoLogo "%~f0?.wsf"')Do Set "naam=%%A"
If Defined naam Echo Uw naam is %naam%&Pause
Exit /B
-->
<Job><Script Language="VBScript">
WScript.Echo InputBox("Naam:")
</Script></Job>
You can pass the variables only via environment variables:
The create_variable.vbs file:
Dim WshShell, WshEnv
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("USER") ' can be either SYSTEM, USER, VOLATILE OR PROCESS
' current value
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
WshEnv("NAAM") = "This text will appear in batch"
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
Set WshEnv = Nothing
Set WshShell = Nothing
Then the batch file show_vbs_variable.bat (you have to open a new cmd.exe to have the new variable there! If you need more infor here is a topic on SO that covers it.:
#echo off
cls
echo %naam%
pause
vbs script for clearing up the variable clearing_variable.vbs:
Dim WshShell, WshEnv
Set WshShell = CreateObject("WScript.Shell")
Set WshEnv = WshShell.Environment("USER") ' can be either SYSTEM, USER, VOLATILE OR PROCESS
' current value
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
'Deleting the env variable
WshEnv.Remove("NAAM")
WScript.Echo "Process: NAAM=" & WshEnv.Item("NAAM")
Set WshEnv = Nothing
Set WshShell = Nothing

Trying to create a shortcut in batch for server

Trying to create a shortcut in batch using a VBScript. I need to change the properties of the path to allow it to run in no-graphics mode.
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo Set shortcut = oWS.CreateShortcut("%USERPROFILE%\Desktop\unturned.exe -batchmode -nographics +secureserver/TheServer.lnk") >> %SCRIPT%
echo shortcut.TargetPath = "D:\SteamLibrary\SteamApps\common\Unturned\Unturned.exe" >> %SCRIPT%
echo shortcut.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
It can't save.
This should did the trick :
#echo off
Set vbsfile=%TEMP%\%RANDOM%.vbs
Set MyFile=D:\SteamLibrary\SteamApps\common\Unturned\Unturned.exe
Set ShorcutName=Unturned
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(CheminApplication,Nom^)
echo Dim objShell,DesktopPath,objShortCut,MyTab
echo Set objShell = CreateObject("WScript.Shell"^)
echo MyTab = Split(CheminApplication,"\"^)
echo If Nom = "" Then
echo Nom = MyTab(UBound(MyTab^)^)
echo End if
echo DesktopPath = objShell.SpecialFolders("Desktop"^)
echo Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo objShortCut.TargetPath = Dblquote(CheminApplication^)
echo ObjShortCut.IconLocation = "Winver.exe,0"
echo objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > %vbsfile%
Start /Wait %vbsfile%
Del %vbsfile%
::****************************************************************************************************
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo Set shortcut = oWS.CreateShortcut("%USERPROFILE%\Desktop\unturned.exe.lnk") >> %SCRIPT%
echo shortcut.TargetPath = "D:\SteamLibrary\SteamApps\common\Unturned\Unturned.exe -batchmode -nographics +secureserver/TheServer" >> %SCRIPT%
echo shortcut.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%

Batch to archive files

I am making a script that can allow me to archive all files of a given directory whom last modified date is superior to 30 days.
The files should be moved to a new folder and this folder must be zipped afterwards.
Aditionaly - and this is a bit crutial - in the archiving process, the files should be grouped by month. The name of the zipped folder should indicate the month and year of the contained files.
Example:
2012_12.zip (contains all files from December 2012) ;
2013_01.zip (contains all files from January 2013)
This is what I have so far:
ECHO OFF
ECHO.
SET /p folder=Which folder you want to archive?
ECHO.
ECHO %folder%
CHDIR %folder%
MKDIR Archive
ROBOCOPY "%folder%" "%folder%\Arquivo" /E /V /ETA /MOVE /XD "%folder%\Archive"
:: Exclude files newer than 30 days
FORFILES /P "%folder%\Archive" /D -31/12/2012 /D +1/12/2012 /C GOTO :ZIP
CALL:ZIP
SET filetozip="%folder%\Archive"
set tempdir=C:\Users\tiago.campos\Documents\OMS\FilesArchiver\tempdir
mkdir %tempdir%
copy %filetozip% %tempdir%
mkdir "%filetozip%\Archive"
rmdir %tempdir%
realdate
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo CreateObject("Scripting.FileSystemObject").CreateTextFile(ZipFile, True).Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo Set objShell = CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo objShell.NameSpace(ZipFile).CopyHere(source) >> _zipIt.vbs
echo wScript.Sleep 2000 >> _zipIt.vbs
CScript _zipIt.vbs %tempdir% "%filetozip%\Archive\2013.01.zip"
del "_zipIt.vbs"
pause
As a bonus feature, it would be very useful if instead of giving the directory as an input, the script would read from a csv file with more than one directory.
I'm a bit lost in the momement.
I thank in advance for every reply!
Since you're already using vbscript for zipping and vbscript is also better for performing arithmetic with dates, might as well do the whole thing in vbscript.
I didn't do the csv thing, but maybe you could call the script with a batch for %%I in (csvfile) do cscript /nologo archive.vbs %%I or similar. If no argument is passed, it archives the current working directory.
' archive.vbs
' usage: cscript archive.vbs (directory, optional)
if not wscript.arguments.count then
dir = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
else
dir = wscript.arguments(0)
if not Right(dir, 1) = "\" then
dir = dir & "\"
end if
end if
set fso = createobject("scripting.filesystemobject")
set shl = createobject("shell.application")
set osh = createobject("wscript.shell")
set files = fso.getFolder(dir).files
dim zips
dim folders
redim zips(-1)
redim folders(-1)
for each file in files
if DateDiff("d", file.datelastmodified, Date()) > 30 then
yyyymm = DatePart("yyyy", file.datelastmodified) & "_" & Right("0" & DatePart("m", file.datelastmodified), 2)
dest = dir & yyyymm & "\"
if not fso.folderexists(dest) then
fso.createFolder dest
zip = dir & yyyymm & ".zip"
redim preserve zips(ubound(zips) + 1)
redim preserve folders(ubound(folders) + 1)
zips(ubound(zips)) = zip
folders(ubound(folders)) = dest
end if
Wscript.echo "Moving " & file & " to " & dest
fso.moveFile file, dest
end if
next
set files = nothing
Wscript.echo "Copying finished."
on error resume next
for i = lbound(zips) to ubound(zips)
Wscript.echo i & ": Zipping " & folders(i) & " to " & zips(i)
set zip = fso.createtextfile(zips(i))
zip.write "PK" & chr(5) & chr(6) & string(18, chr(0))
zip.close
set zip = Nothing
shl.namespace(zips(i)).copyhere shl.namespace(folders(i)).items
do until shl.namespace(zips(i)).items.count = shl.namespace(folders(i)).items.count
wscript.sleep 100
loop
' This method of deleting folders is more reliable than fso.deletefolder
' for paths with long filenames.
osh.run "cmd /c rmdir /q /s """ & folders(i) & """", 1, true
next
Wscript.Echo "Done."

Resources