Batch Command Line to Eject CD Tray? - windows

I'm currently trying to move my CD's of backup to my Backup HDD.
To automate the task I'm trying to create a batch to copy the files with the label of the CD than eject the media.
The code looks like this so far:
#echo off
SET dest=F:\Backup\
d:
:: routine to retrieve volume label.
for /f "tokens=1-5*" %%1 in ('vol') do (
set vol=%%6 & goto done
)
:done
:: create destination folder
set dest=%dest%%vol%
mkdir "%dest%"
:: copy to destiny folder
xcopy "d:" "%dest%" /i /s /exclude:c:\excludes.txt
::eject CD
c:
I'm stuck at eject part. I'm trying to eject the CD because I want a clear line to draw my attention when the copy finished (I thought opening the tray to be a good one).
Any ideas how to do it using Batch? Or any other ways to "draw the attention" to the end of the copy event?
Thanks :)

if you have no installed media player or anti virus alarms check my other answer.
:sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul
'& cls
'& cscript /nologo /E:vbscript %~f0
'& pause
Set oWMP = CreateObject("WMPlayer.OCX.7" )
Set colCDROMs = oWMP.cdromCollection
if colCDROMs.Count >= 1 then
For i = 0 to colCDROMs.Count - 1
colCDROMs.Item(i).Eject
Next ' cdrom
End If
This is a batch/vbscript hybrid (you need to save it as a batch) .I don't think is possible to do this with simple batch.On windows 8/8.1 might require download of windows media player (the most right column).Some anti-virus programs could warn you about this script.

I know this question is old, but I wanted to share this:
#echo off
echo Set oWMP = CreateObject("WMPlayer.OCX.7") >> %temp%\temp.vbs
echo Set colCDROMs = oWMP.cdromCollection >> %temp%\temp.vbs
echo For i = 0 to colCDROMs.Count-1 >> %temp%\temp.vbs
echo colCDROMs.Item(i).Eject >> %temp%\temp.vbs
echo next >> %temp%\temp.vbs
echo oWMP.close >> %temp%\temp.vbs
%temp%\temp.vbs
timeout /t 1
del %temp%\temp.vbs
just make sure you don't have a file called "temp.vbs" in your Temp folder. This can be executed directly through a cmd, you don't need a batch, but I don't know any command like "eject E:\". Remember that this will eject all CD trays in your system.

UPDATE:
A script that supports also ejection of a usb sticks - ejectjs.bat:
::to eject specific dive by letter
call ejectjs.bat G
::to eject all drives that can be ejected
call ejectjs.bat *
A much better way that does not require windows media player and is not recognized by anti-virus programs (yet) .Must be saves with .bat extension:
#cScript.EXE //noLogo "%~f0?.WSF" //job:info %~nx0 %*
#exit /b 0
<job id="info">
<script language="VBScript">
if WScript.Arguments.Count < 2 then
WScript.Echo "No drive letter passed"
WScript.Echo "Usage: "
WScript.Echo " " & WScript.Arguments.Item(0) & " {LETTER|*}"
WScript.Echo " * will eject all cd drives"
WScript.Quit 1
end if
driveletter = WScript.Arguments.Item(1):
driveletter = mid(driveletter,1,1):
Public Function ejectDrive (drvLtr)
Set objApp = CreateObject( "Shell.Application" ):
Set objF=objApp.NameSpace(&H11&):
'WScript.Echo(objF.Items().Count):
set MyComp = objF.Items():
for each item in objF.Items() :
iName = objF.GetDetailsOf (item,0):
iType = objF.GetDetailsOf (item,1):
iLabels = split (iName , "(" ) :
iLabel = iLabels(1):
if Ucase(drvLtr & ":)") = iLabel and iType = "CD Drive" then
set verbs=item.Verbs():
set verb=verbs.Item(verbs.Count-4):
verb.DoIt():
item.InvokeVerb replace(verb,"&","") :
ejectDrive = 1:
exit function:
end if
next
ejectDrive = 2:
End Function
Public Function ejectAll ()
Set objApp = CreateObject( "Shell.Application" ):
Set objF=objApp.NameSpace(&H11&):
'WScript.Echo(objF.Items().Count):
set MyComp = objF.Items():
for each item in objF.Items() :
iType = objF.GetDetailsOf (item,1):
if iType = "CD Drive" then
set verbs=item.Verbs():
set verb=verbs.Item(verbs.Count-4):
verb.DoIt():
item.InvokeVerb replace(verb,"&","") :
end if
next
End Function
if driveletter = "*" then
call ejectAll
WScript.Quit 0
end if
result = ejectDrive (driveletter):
if result = 2 then
WScript.Echo "no cd drive found with letter " & driveletter & ":"
WScript.Quit 2
end if
</script>
</job>

Requiring administrator's rights is too abusing :)
I am using wizmo:
https://www.grc.com/WIZMO/WIZMO.HTM

Related

How do I create a shortcut via command-line in Windows?

I want my .bat script (test.bat) to create a shortcut to itself so that I can copy it to my windows 8 Startup folder.
I have written this line of code to copy the file but I haven't yet found a way to create the said shortcut, as you can see it only copies the script.
xcopy "C:\Users\Gabriel\Desktop\test.bat" "C:\Users\Gabriel\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"
Can you help me out?
You could use a PowerShell command. Stick this in your batch script and it'll create a shortcut to %~f0 in %userprofile%\Start Menu\Programs\Startup:
powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\%~n0.lnk');$s.TargetPath='%~f0';$s.Save()"
If you prefer not to use PowerShell, you could use mklink to make a symbolic link. Syntax:
mklink saveShortcutAs targetOfShortcut
See mklink /? in a console window for full syntax, and this web page for further information.
In your batch script, do:
mklink "%userprofile%\Start Menu\Programs\Startup\%~nx0" "%~f0"
The shortcut created isn't a traditional .lnk file, but it should work the same nevertheless. Be advised that this will only work if the .bat file is run from the same drive as your startup folder. Also, apparently admin rights are required to create symbolic links.
Cannot be done with pure batch.Check the shortcutJS.bat - it is a jscript/bat hybrid and should be used with .bat extension:
call shortcutJS.bat -linkfile "%~n0.lnk" -target "%~f0" -linkarguments "some arguments"
With -help you can check the other options (you can set icon , admin permissions and etc.)
Rohit Sahu's answer worked best for me in Windows 10. The PowerShell solution ran, but no shortcut appeared. The JScript solution gave me syntax errors. I didn't try mklink, since I didn't want to mess with permissions.
I wanted the shortcut to appear on the desktop.
But I also needed to set the icon, the description, and the working directory.
Note that MyApp48.bmp is a 48x48 pixel image.
Here's my mod of Rohit's solution:
#echo off
cd c:\MyApp
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%userprofile%\Desktop\MyApp.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "C:\MyApp\MyApp.bat" >> CreateShortcut.vbs
echo oLink.WorkingDirectory = "C:\MyApp" >> CreateShortcut.vbs
echo oLink.Description = "My Application" >> CreateShortcut.vbs
echo oLink.IconLocation = "C:\MyApp\MyApp48.bmp" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs
The best way is to run this batch file.
open notepad and type:-
#echo off
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "GIVETHEPATHOFLINK.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "GIVETHEPATHOFTARGETFILEYOUWANTTHESHORTCUT" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
del CreateShortcut.vbs
Save as filename.bat(be careful while saving select all file types)
worked well in win XP.
Nirsoft's NirCMD can create shortcuts from a command line, too. (Along with a pile of other functions.) Free and available here:
http://www.nirsoft.net/utils/nircmd.html
Full instructions here:
http://www.nirsoft.net/utils/nircmd2.html#using (Scroll down to the "shortcut" section.)
Yes, using nircmd does mean you are using another 3rd-party .exe, but it can do some functions not in (most of) the above solutions (e.g., pick a icon # in a dll with multiple icons, assign a hot-key, and set the shortcut target to be minimized or maximized).
Though it appears that the shortcutjs.bat solution above can do most of that, too, but you'll need to dig more to find how to properly assign those settings. Nircmd is probably simpler.
link.vbs
set fs = CreateObject("Scripting.FileSystemObject")
set ws = WScript.CreateObject("WScript.Shell")
set arg = Wscript.Arguments
linkFile = arg(0)
set link = ws.CreateShortcut(linkFile)
link.TargetPath = fs.BuildPath(ws.CurrentDirectory, arg(1))
link.Save
command
C:\dir>link.vbs ..\shortcut.txt.lnk target.txt
To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.
powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"
Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357
I present a small hybrid script [BAT/VBS] to create a desktop shortcut.
And you can of course modifie it to your purpose.
#echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo Dim objShell,DesktopPath,objShortCut,MyTab
echo Set objShell = CreateObject("WScript.Shell"^)
echo MyTab = Split(ApplicationPath,"\"^)
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(ApplicationPath^)
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 ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test
Pause > Nul
::********************************************************************************************
I would like to propose different solution which wasn't mentioned here which is using .URL files:
set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%
Notes:
By default .url files are intended to open web pages but they are working fine for any properly constructed URI
Microsoft Windows does not display the .url file extension even if "Hide extensions for known file types" option in Windows Explorer is disabled
IconFile and IconIndex are optional
For reference you can check An Unofficial Guide to the URL File Format of Edward Blake
I created a VB script and run it either from command line or from a Java process.
I also tried to catch errors when creating the shortcut so I can have a better error handling.
Set oWS = WScript.CreateObject("WScript.Shell")
shortcutLocation = Wscript.Arguments(0)
'error handle shortcut creation
On Error Resume Next
Set oLink = oWS.CreateShortcut(shortcutLocation)
If Err Then WScript.Quit Err.Number
'error handle setting shortcut target
On Error Resume Next
oLink.TargetPath = Wscript.Arguments(1)
If Err Then WScript.Quit Err.Number
'error handle setting start in property
On Error Resume Next
oLink.WorkingDirectory = Wscript.Arguments(2)
If Err Then WScript.Quit Err.Number
'error handle saving shortcut
On Error Resume Next
oLink.Save
If Err Then WScript.Quit Err.Number
I run the script with the following commmand:
cscript /b script.vbs shortcutFuturePath targetPath startInProperty
It is possible to have it working even without setting the 'Start in' property in some cases.
Based on Rohit's answer, I created this batch script which accepts the input parameters: AppPath, AppName, AppExtension and ShortcutDestinationPath.
MakeShortcut.bat:
#echo off
set AppPath=%~1
set AppName=%~2
set AppExtension=%~3
set ShortcutDestinationPath=%~4
cd %AppPath%
echo Set oWS = WScript.CreateObject("WScript.Shell") > CreateShortcut.vbs
echo sLinkFile = "%ShortcutDestinationPath%\%AppName%.lnk" >> CreateShortcut.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> CreateShortcut.vbs
echo oLink.TargetPath = "%AppPath%\%AppName%.%AppExtension%" >> CreateShortcut.vbs
echo oLink.WorkingDirectory = "%AppPath%" >> CreateShortcut.vbs
echo oLink.Description = "%AppName%" >> CreateShortcut.vbs
echo oLink.IconLocation = "%AppPath%\%AppName%.bmp" >> CreateShortcut.vbs
echo oLink.Save >> CreateShortcut.vbs
cscript CreateShortcut.vbs
rem del CreateShortcut.vbs
Example usage to create a shortcut to C:\Apps\MyApp.exe in the folder C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp:
MakeShortcut.bat "C:\Apps" "MyApp" "exe" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp"

How to End a VBScript Called from a Batch File and loop through the Batch File

Currently I have a batch file that calls a VBScript and executes the script and exits from that script into the command prompt window that I called the batch file from. I am wanting to return to the batch file from the VBScript and loop back into the beginning of the batch file and ask for the information from the user again and then go back into the script and repeat. I would also like to query the user as to whether they would like to quit or repeat after the VBscript has been run.
Here is my batch file:
#echo off
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
Set /P datafile=Please enter data file to be analyzed:
Set /P filename=Please enter name for canvas file:
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
And here is my VBScript (Disregard the SendKeys method, I understand how unreliable it is and will modify this later to not use it):
Set wshShell = CreateObject("Wscript.Shell")
Set args = WScript.Arguments
arg1 = args.Item(0)
Dim filename
filename = ""&arg1&""
WshShell.AppActivate "Command Prompt"
WshShell.SendKeys "root -b"
WshShell.SendKeys "~"
WshShell.AppActivate "ROOT session"
WshShell.SendKeys ".x analysis.C"
WshShell.SendKeys "~"
WshShell.SendKeys ".x double_gaus.C"
WshShell.SendKeys "~"
WshShell.AppActivate "ROOT session"
WshShell.SendKeys "c1->SaveAs{(}"""&filename&"""{)}"
WshShell.SendKeys "~"
WshShell.SendKeys ".q"
WshShell.SendKeys "~"
WScript.Quit
I have tried various ways of using the IF ERRORLEVEL command and keeping in mind that it must be in descending order when checked, but nothing is working.
#echo off
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
:loop
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
set "datafile="
Set /P datafile=Please enter data file to be analyzed:
if not defined datafile echo all done - exiting&goto :eof
set "filename="
Set /P filename=Please enter name for canvas file:
if not defined filename echo all done - exiting&goto :eof
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
goto loop
This should get you going.
Can't see what errorlevels have to do with anything. You appear not to be setting the vbscript exit code (need WScript.Quit yourerrorlevel else it will exit with errorlevel 0, I am told)
If you clear the values before they are input, then you can take advantage of the set /p behaviour that the value will remain unchanged if you simply reply with Enter
You can also use this characteristic to establish a default value, if that suits.
OR you could define a specific exit codeword like quit or exit. Using this method, you'd code a line
if /i "%var%"=="exit" echo Bye-bye&goto :eof
where the quotes protect against an empty or space-containing entry by the user into var, the & is an inline statement-separator and :eof is a special label predefined and understood by cmd to mean end of file (the colon is required)
This has a loop and a method to exit from the loop.
#echo off
:loop
C:
cd C:\Users\Jared\Documents\Research\jared
Set "File=basic.dat"
Del "%File%" 2>NUL & If exist "%File%" (
Echo [+] File failed to delete: "%File%" >> "Report.txt"
)
"set datafaile="
Set /P datafile=Please enter data file to be analyzed or press Enter to Quit:
if not defined datafile goto :EOF
Set /P filename=Please enter name for canvas file:
mklink basic.dat %datafile%
cscript Root_VBS_Script_1.vbs %filename%
goto :loop
As #brianadams suggested, there's no need for a batch script here. You can do the entire prompting and looping in VBScript and shell out for external commands like mklink.
Set sh = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
sh.CurrentDirectory = "C:\Users\Jared\Documents\Research\jared"
basicfile = "basic.dat"
Do
If fso.FileExists(basicfile) Then
On Error Resume Next
fso.DeleteFile basicfile, True
If Err Then fso.OpenTextFile("Report.txt", 8, True).WriteLine _
"[+] File failed to delete: " & qq(basicfile)
On Error Goto 0
End If
datafile = InputBox("Please enter data file to be analyzed:")
filename = InputBox("Please enter name for canvas file:")
sh.Run "cmd /c mklink " & qq(basicfile) & " " & qq(datafile)
sh.AppActivate "Command Prompt"
sh.SendKeys "root -b"
'...
Loop

Enable Logs in script

I am new in scripting, I wrote below script to create folders on multiple computers and I need to create log file which show success and failure status of task.
Can some one help me.
Script :
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\CL_Repair\Computers.txt")
Do Until objFile.AtEndOfStream
strComputer = objFile.ReadLine
Set objWMIService = GetObject _
("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
errReturn = objWMIService.Create _
("cmd.exe /c md c:\CL_Repair", Null, Null, intProcessID)
Loop
MsgBox("Folder = CL_Repair Created on Computers")
I think this is what you are looking for.. I have worked with Bill Stewart many years ago on some scripting items and he is a reliable resource..
http://social.technet.microsoft.com/Forums/windows/en-US/52873f35-5d55-498c-949e-da8ceb1df980/vbscript-write-error-to-log-file
Two items of notice:
On Error Resume Next
Is a line you would need to add to your VBScript.
Setup a batch file to run:
#echo off
ECHO %COMPUTERNAME% >> C:\Scripts\errors.txt
cscript C:\Scripts\myScript.vbs 2>> C:\Scripts\errors.txt
Now, this should trap issues seen and should log for you.
Ok.. You asked to have a list (text) list of servers.. Try something like this.. You really don't need the VBScript to do this..
:: http://www.robvanderwoude.com/files/servers_nt.txt
:: Check all servers in the list
FOR /F "tokens=*" %%A IN ('TYPE servers.txt') DO (
ECHO %%A >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\. ECHO CREATING FOLDER \\%%A\c$\CL_Repair >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\. MD \\%%A\c$\CL_Repair
IF NOT EXIST \\%%A\c$\CL_Repair\somefile.exe ECHO copying somefile.exe \\%%A\c$\CL_Repair >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\somefile.exe copy c:\CL_Repair\somefile.exe \\%%A\c$\CL_Repair
IF NOT EXIST \\%%A\c$\CL_Repair\anotherfile.bat ECHO copying anotherfile.bat \\%%A\c$\CL_Repair >> C:\Scripts\errors.txt
IF NOT EXIST \\%%A\c$\CL_Repair\anotherfile.bat copy c:\CL_Repair\anotherfile.bat \\%%A\c$\CL_Repair)
GOTO End
:END
EXIT

How to create shortcut icon using BATCH file which run my Java application?

I have a windows.bat file which is actually my custom installer. When everything is installed i finally need to create one desktop shortcut icon, which has icon, and link to execute my Java jar. I successfully made one but its using VBS, what i am trying to do now is avoid using VBS but do it completely using BATCH file only. But how do i make this following in BATCH file?
Example:
1) Create an empty file vbs.vbs and paste this code to desktop
set WshShell = WScript.CreateObject("WScript.Shell" )
strDesktop = WshShell.SpecialFolders("AllUsersDesktop" )
set oShellLink = WshShell.CreateShortcut(strDesktop & "\StackOverflow shortcut.lnk")
oShellLink.TargetPath = "c:\application folder\application.exe"
oShellLink.WindowStyle = 1
oShellLink.IconLocation = "c:\application folder\application.ico"
oShellLink.Description = "Shortcut Script"
oShellLink.WorkingDirectory = "c:\application folder"
oShellLink.Save
2) Double click the the vbs.vbs file and instantly it creates a shortcut file
in the desktop tested in Windows XP works
But how do i skip the VBS process and do it completely from my BATCH script?
(Is there any way using RUNDLL32.EXE APPWIZ.CPL,NewLinkHere (Dest))
This was asked and answered before here:
creating a shortcut for a exe from a batch file
One of the provided answers (not the accepted one) has this link:
http://www.robvanderwoude.com/amb_shortcutsnt.php
The relevant script is:
#echo off & setlocal
::For Windows NT 4.0 users only!!!
::Creates LNK and PIF files from the command line.
::Author: Walter Zackery
if not %1[==[ if exist %1 goto start
echo You must pass the path of a file or folder to the
echo batch file as a shortcut target.
if not %1[==[ echo %1 is not an existing file or folder
(pause & endlocal & goto:eof)
:start
(set hkey=HKEY_CURRENT_USER\Software\Microsoft\Windows)
(set hkey=%hkey%\CurrentVersion\Explorer\Shell Folders)
(set inf=rundll32 setupapi,InstallHinfSection DefaultInstall)
start/w regedit /e %temp%\#57#.tmp "%hkey%"
for /f "tokens=*" %%? in (
'dir/b/a %1? 2^>nul') do (set name=%%~nx?)
for /f "tokens=2* delims==" %%? in (
'findstr/b /i """desktop"""= %temp%\#57#.tmp') do (set d=%%?)
for /f "tokens=2* delims==" %%? in (
'findstr/b /i """programs"""= %temp%\#57#.tmp') do (set p=%%?)
(set d=%d:\\=\%) & (set p=%p:\\=\%)
if not %2[==[ if exist %~fs2\nul (set d=%~fs2)
if not %2[==[ if exist %~fs2nul (set d=%~fs2)
set x=if exist %2\nul
if not %2[==[ if not %d%==%2 %x% if "%~p2"=="\" set d=%2
echo %d%|find ":\" >nul||(set d=%d%\)
(set file=""""""%1"""""")
for /f "tokens=1 delims=:" %%? in ("%file:"=%") do set drive=%%?
(set progman=setup.ini, progman.groups,,)
echo > %temp%\#k#.inf [version]
echo >>%temp%\#k#.inf signature=$chicago$
echo >>%temp%\#k#.inf [DefaultInstall]
echo >>%temp%\#k#.inf UpdateInis=Addlink
echo >>%temp%\#k#.inf [Addlink]
echo >>%temp%\#k#.inf %progman% ""group200="}new{"""
echo >>%temp%\#k#.inf setup.ini, group200,, """%name%"",%file%
start/w %inf% 132 %temp%\#k#.inf
del %temp%\#k#.inf %temp%\#57#.tmp
move %p%\"}new{\*.*" %d% >nul 2>&1
rd %p%\}new{ 2>nul
move %p%\}new{.lnk %d%\"drive %drive%.lnk" >nul 2>&1
endlocal
Not sure if that will fly all the way into Win7 and 8
In the end I decided to write the correct script, because no solution works for me
You will need two fileLocal Settings\
first
createSCUT.bat
#echo on
set VBS=createSCUT.vbs
set SRC_LNK="shortcut1.lnk"
set ARG1_APPLCT="C:\Program Files\Google\Chrome\Application\chrome.exe"
set ARG2_APPARG="--profile-directory=QuteQProfile 25QuteQ"
set ARG3_WRKDRC="C:\Program Files\Google\Chrome\Application"
set ARG4_ICOLCT="%USERPROFILE%\Local Settings\Application Data\Google\Chrome\User Data\Profile 28\Google Profile.ico"
cscript %VBS% %SRC_LNK% %ARG1_APPLCT% %ARG2_APPARG% %ARG3_WRKDRC% %ARG4_ICOLCT%
and second
createSCUT.vbs
Set objWSHShell = WScript.CreateObject("WScript.Shell")
set objWSHShell = CreateObject("WScript.Shell")
set objFso = CreateObject("Scripting.FileSystemObject")
If WScript.arguments.count = 5 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir IconLocation"
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))
sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))
sIconLocation = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(4))
objSC.TargetPath = sTargetPath
rem http://www.bigresource.com/VB-simple-replace-function-5bAN30qRDU.html#
objSC.Arguments = Replace(sArguments, "QuteQ", Chr(34))
rem http://msdn.microsoft.com/en-us/library/f63200h0(v=vs.90).aspx http://msdn.microsoft.com/en-us/library/267k4fw5(v=vs.90).aspx
objSC.WorkingDirectory = sWorkingDirectory
objSC.Description = "Love Peace Bliss"
rem 1 restore 3 max 7 min
objSC.WindowStyle = "3"
rem objSC.Hotkey = "Ctrl+Alt+e";
objSC.IconLocation = sIconLocation
objSC.Save
WScript.Quit
end If
If WScript.arguments.count = 4 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath arguments workingDir "
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sArguments = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(2))
sWorkingDirectory = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(3))
objSC.TargetPath = sTargetPath
objSC.Arguments = Replace(sArguments, "QuteQ", Chr(34))
objSC.WorkingDirectory = sWorkingDirectory
objSC.Description = "Love Peace Bliss"
objSC.WindowStyle = "3"
objSC.Save
WScript.Quit
end If
If WScript.arguments.count = 2 then
WScript.Echo "usage: makeshortcut.vbs shortcutPath targetPath"
sShortcut = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(0))
set objSC = objWSHShell.CreateShortcut(sShortcut)
sTargetPath = objWSHShell.ExpandEnvironmentStrings(WScript.Arguments.Item(1))
sWorkingDirectory = objFso.GetAbsolutePathName(sShortcut)
objSC.TargetPath = sTargetPath
objSC.WorkingDirectory = sWorkingDirectory
objSC.Save
WScript.Quit
end If

How to set environment variables in vbs that can be read in calling batch script

I have a batch file that calls a vbscript file. I am trying to have the vbscript file change an environment variable that is later used in the batch file that calls the vbscript file.
Here are snippetes from the files.
Parent.bat
Set Value="Initial Value"
cscript Child.vbs
ECHO Value = %VALUE%
Child.vbs
Set wshShell = CreateObject( "WScript.Shell" )
Set wshSystemEnv = wshShell.Environment( "Process" )
wshSystemEnv("VALUE") = "New Value"
You can't. A process can pass environment variables to child processes, but not to its parent - and in this case the parent is cmd.exe, which is running your Parent.bat file.
There are of course other ways to communicate information back to the parent batch file - outputting to stdout or a file is an obvious way, e.g.
== Child.vbs ===
WScript.echo "New Value"
== Parent.cmd ===
for /f "tokens=*" %%i in ('cscript //nologo child.vbs') do set Value=%%i
echo %Value%
yes, you can.... however, you'll have to resetvars in your session. see the following link:
Is there a command to refresh environment variables from the command prompt in Windows?
'RESETVARS.vbs
Set oShell = WScript.CreateObject("WScript.Shell")
filename = oShell.ExpandEnvironmentStrings("%TEMP%\resetvars.bat")
Set objFileSystem = CreateObject("Scripting.fileSystemObject")
Set oFile = objFileSystem.CreateTextFile(filename, TRUE)
set oEnv=oShell.Environment("System")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = oEnv("PATH")
set oEnv=oShell.Environment("User")
for each sitem in oEnv
oFile.WriteLine("SET " & sitem)
next
path = path & ";" & oEnv("PATH")
oFile.WriteLine("SET PATH=" & path)
oFile.Close
This is how I did it:
SET oShell = CREATEOBJECT("Wscript.Shell")
dim varSet
SET varSet = NOTHING
SET varSet = oShell.Environment("SYSTEM")
varSet("WinVer") = "6.0.2008"
Then in a separate VB script (resetvars.vbs) I called from CMD script:
cscript //nologo \\%APPSERVER%\apps\IE9.0\restartvars.vbs
call %TEMP%\resetvars.bat
I don't think you can do this. At least, you would need to mess with the environment block in the calling process, and there's no guarantee that it will respect this...
Ho about this:
#echo off
set vbsFile=%temp%\createguid.vbs
call :CreateVbs
call :GetGuid NewGuid
echo.%NewGuid%
del %vbsFile%>nul
GOTO:EOF
:CreateVbs
echo.set obj = CreateObject("Scriptlet.TypeLib")>%vbsFile%
echo.WScript.StdOut.WriteLine obj.GUID>>%vbsFile%
GOTO:EOF
:GetGuid
for /f "tokens=*" %%i in ('cscript //nologo %vbsFile%') do set %1=%%i
GOTO:EOF
It is not pure batch script but works ok.
#echo off&color 4a&title %~n0&AT>NUL
IF %ERRORLEVEL% EQU 0 (
goto 2
) ELSE (
echo.
)
if not "%minimized%"=="" goto 1
set minimized=true & start /min cmd /C "%~dpnx0"&cls&exit
:1
wmic process where name="cmd.exe" CALL setpriority "realtime">nul&echo set shell=CreateObject("Shell.Application") > %~n0.vbs&echo shell.ShellExecute "%~dpnx0",,"%CD%", "runas", 1 >> %~n0.vbs&echo set shell=nothing >> %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit
:2
echo %~dpnx0 admin mode look up&wmic process where name="cmd.exe" CALL setpriority "realtime"&timeout 3 /NOBREAK>nul
:3
echo x=msgbox("end of line" ,48, "%~n0") > %~n0.vbs&start %~n0.vbs /realtime&timeout 1 /NOBREAK>nul& del /Q %~n0.vbs&cls&exit

Resources