Why is my entire batch script running as a SETLOCAL command? - windows

I don't understand what I'm doing wrong, the output is always the entire script, with an Invalid parameter to setlocal error! This is probably just a silly mistake, but it's making me crazy.
SETLOCAL ENABLEDELAYEDEXPANSION
REM Obtain username of logged in user
SET loggedinuser=%USERNAME%
REM Create temporary vbscript to obtain user OU
echo Const ADS_SCOPE_SUBTREE = 2 >temp.vbs
echo. >>temp.vbs
echo Set objConnection = CreateObject("ADODB.Connection") >>temp.vbs
echo Set objCommand = CreateObject("ADODB.Command") >>temp.vbs
echo objConnection.Provider = "ADsDSOObject" >>temp.vbs
echo objConnection.Open "Active Directory Provider" >>temp.vbs
echo Set objCommand.ActiveConnection = objConnection >>temp.vbs
echo. >>temp.vbs
echo objCommand.Properties("Page Size") = 1000 >>temp.vbs
echo objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE >>temp.vbs
echo. >>temp.vbs
echo objCommand.CommandText = _ >>temp.vbs
echo ^"SELECT distinguishedName FROM ^'LDAP://dc=test,dc=com^' ^" ^& _ >>temp.vbs
echo "WHERE objectCategory='user' " ^& _ >>temp.vbs
echo "AND sAMAccountName='!loggedinuser!'" >>temp.vbs
echo Set objRecordSet = objCommand.Execute >>temp.vbs
echo. >>temp.vbs
echo objRecordSet.MoveFirst >>temp.vbs
echo Do Until objRecordSet.EOF >>temp.vbs
echo strDN = objRecordSet.Fields("distinguishedName").Value >>temp.vbs
echo arrPath = Split(strDN, ",") >>temp.vbs
echo intLength = Len(arrPath(1)) >>temp.vbs
echo intNameLength = intLength - 3 >>temp.vbs
echo Wscript.Echo Right(arrPath(1), intNameLength) >>temp.vbs
echo objRecordSet.MoveNext >>temp.vbs
echo Loop >>temp.vbs
REM Save backup of old printer list, just in case
echo Creating a backup list of current printers, please wait...
wmic printer list brief /format:csv > \\networkshare\userfiles\!loggedinuser!\oldprinterlist.txt
echo Backup list completed.
REM Set the OU variable by running the vbscript
echo Discovering your department...
FOR /F "delims=" %%a in ('cscript.exe /nologo temp.vbs') do #set OU=%%a
echo Adding printers for %OU%
REM Perform new printer install based on OU
if %OU%==MIS (
set printer1=Printer_1_Yo
set printer2=Printer_2_Yo
set printer3=Printer_3_Yo
echo Adding %printer1%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer1%
echo %printer1% added. Adding %printer2%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer2%
echo %printer2% added. Adding %printer3%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer3%
echo %printer3% added. All printers are ready to use!
)
REM Delete printers that were on job
echo Deleting old printers from testserver, please wait...
wmic printer where servername=\\\\testserver delete
echo Deletion complete.
echo. If you would like to add more printers, please visit the Printers page on the intranet.
echo. Press any key to close this window.
pause>temp.txt
del temp.txt
del temp.vbs
After further testing, it seems that the wmic printer where line doesn't work properly, and I will fix that soon (suggestions welcome)... but is that the cause of the entire script falling apart? I'm aware that the vbscript portion is a little odd, but I don't think that's the issue either. Please correct me if I'm wrong!

If your script does NOT start with #ECHO OFF command, then you will see in the screen the fully script contents when it runs.
I want to make good use of this post, so I modified your script in order to make the creation of the temp.vbs file much cleaner, although this point is not directly related to your problem. However, when I tested the Batch file below with a GOTO :EOF command inserted after the creation of the temp.vbs file, it correctly runs with no "setlocal" error!
EDIT: I realized that original script uses loggedinuser variable to hardcode its value in the creation of the temp.vbs program, that is the reason because the file is created and deleted each time. My original translation does not account for this detail.
I modified the Batch file below to pass the value of loggedinuser from Batch to VBS section in the parameter. This way, the .vbs program could be created just once with a more appropriate name.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
REM Obtain username of logged in user
SET loggedinuser=%USERNAME%
REM Create temporary vbscript to obtain user OU, if not exists
if not exist getUserOU.vbs (
for /F "delims=:" %%a in ('findstr /N "^:VBS_Section" "%~F0"') do set n=%%a
more +!n! < "%~F0" > getUserOU.vbs
)
REM Save backup of old printer list, just in case
echo Creating a backup list of current printers, please wait...
wmic printer list brief /format:csv >
\\networkshare\userfiles\!loggedinuser!\oldprinterlist.txt
echo Backup list completed.
REM Set the OU variable by running the vbscript
echo Discovering your department...
FOR /F "delims=" %%a in ('cscript.exe //nologo getUserOU.vbs "%loggedinuser%"') do #set OU=%%a
echo Adding printers for %OU%
REM Perform new printer install based on OU
if %OU%==MIS (
set printer1=Printer_1_Yo
set printer2=Printer_2_Yo
set printer3=Printer_3_Yo
echo Adding %printer1%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer1%
echo %printer1% added. Adding %printer2%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer2%
echo %printer2% added. Adding %printer3%, please wait...
wmic printer call addprinterconnection \\newprintserver\%printer3%
echo %printer3% added. All printers are ready to use!
)
REM Delete printers that were on job
echo Deleting old printers from testserver, please wait...
wmic printer where servername=\\\\testserver delete
echo Deletion complete.
echo. If you would like to add more printers, please visit the Printers page on the intranet.
echo. Press any key to close this window.
pause>temp.txt
del temp.txt
goto :EOF
:VBS_Section
Const ADS_SCOPE_SUBTREE = 2
Set objConnection = CreateObject("ADODB.Connection")
Set objCommand = CreateObject("ADODB.Command")
objConnection.Provider = "ADsDSOObject"
objConnection.Open "Active Directory Provider"
Set objCommand.ActiveConnection = objConnection
objCommand.Properties("Page Size") = 1000
objCommand.Properties("Searchscope") = ADS_SCOPE_SUBTREE
objCommand.CommandText = _
"SELECT distinguishedName FROM 'LDAP://dc=test,dc=com' " & _
"WHERE objectCategory='user' " & _
"AND sAMAccountName='" & WScript.Arguments(0) & "'"
Set objRecordSet = objCommand.Execute
objRecordSet.MoveFirst
Do Until objRecordSet.EOF
strDN = objRecordSet.Fields("distinguishedName").Value
arrPath = Split(strDN, ",")
intLength = Len(arrPath(1))
intNameLength = intLength - 3
Wscript.Echo Right(arrPath(1), intNameLength)
objRecordSet.MoveNext
Loop

For your wmic printer command use:
wmic printer where 'servername="\\\\testserver"'
If that doesn't work, swap the single and double quotes. I'm not at a computer atm, so I'm going from memory. Also, you don't have to go through all that creating vbscript to get a ou. Wmic can query ldap.
WMIC /NAMESPACE:\\root\directory\ldap PATH ds_user GET ds_distinguishedname
Here is my version of your script.
#echo off
setlocal enabledelayedexpansion
set q=wmic /NAMESPACE:\\root\directory\ldap PATH ds_user Where "ds_samaccountname^='!username!'" get ds_distinguishedname
for /f "skip=1 tokens=3 delims==" %%a in ('%q%') do (
for /f "tokens=1 delims=," %%b in ("%%a") do set ou=%%b
)
:: Save backup of old printer list, just in case
set share=\\networkshare\userfiles
if not exist "%share%\!username!" md "%share%\!username!"
set printlist="%share%\!username!\oldprinterlist.txt"
echo Creating a backup list of current printers, please wait...
wmic printer list brief /format:csv > %printlist%
echo Backup list completed.
::Perform new printer install based on OU
IF %ou%==MIS (
call :addprinter Printer_1_Yo Testserver
call :addprinter Printer_2_Yo Testserver
call :addprinter Printer_3_Yo Testserver
)
::Delete printers that were on job
echo.
echo Deleting old printers from testserver, please wait...
wmic printer where "servername='\\\\testserver'" delete
echo Deletion complete.
echo.
echo. If you would like to add more printers, please visit the Printers page on the intranet.
echo. Press any key to close this window.
pause>nul
goto :eof
:addprinter prn server
echo.
echo Adding %1, please wait...
wmic printer call addprinterconnection \\%2\%1

Related

Send file(s) by email on a regular basis via batch file

I have a beginner's problem. I have a remote computer which collects data (amateur metheorology stuff). Data is stored on a daily basis in a text file. Each file is named after its date: 28_02-2014.txt, 01_03_2014.txt etc.
Can anyone help me create a batch file which would somehow send such a text file over email automatically. Even an option of creating a zip file from all the txt files will be OK. I can delete the folder once a month, so even sending a zip file with 31 text files inside won't affect bandwidth (probably 300kb per month).
My problems so far:
Windows 7
I don't know how to create a batch file which would ZIP all the files in one folder.
I don't know how to send an automatic e-mail. The task scheduler doesn't allow to input server authentication (user/pass). I can only type the SMTP server name and that's it.
Even if I manage to send e-mail somehow through the task manager, I would have to create an action for every day, which doesn't seem ideal.
Please, could anyone help me with this? Whichever solution is simpler: either sending the newest file from a specific folder or zipping the whole folder into a file and sending it.
XP Pro and higher for the date routine using WMIC:
In this line set fileattach="d:\myfolder\%datestamp%.txt" change the folder, and the datestamp is set to dd_mm-yyyy format so the filename should work for you as it is.
The text file will be attached but not zipped up.
Alter the server settings and passwords to suit you in the block of set statements, and test it.
You can schedule the batch file on a daily cycle, if that suits you.
#echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%DD%_%MM%-%YYYY%"
:: email.bat :::::::::::::::::::::::::::::::::::::::::::::::::::::
#echo off
setlocal
:: use these settings to send from a gmail account
:: set port=465 and set SSL=True
:: use these settings for standard email SMTP port and no encryption
:: set port=25 and set SSL=False
:: Change these following items to use the same variables all the time
:: or use the command line to pass all the variables
set Port=25
set SSL=False
set From="myemail#myemailserver.com"
set To="recipient#server.com"
set Subject="Subject line"
set Body="Email Body in one line"
set SMTPServer="mailservername.myemailserver.com"
set User="username"
set Pass="password"
set fileattach="d:\myfolder\%datestamp%.txt"
:: This section sets the command line arguments
:: use this format: CALL email.bat "myname#gmail.com" "RecipientEmailAddress#server.com" "Subject line" "Email Body in one line" "smtp.gmail.com" "myname#gmail.com" "password" "d:\folder\filename to attach.txt"
if "%~7" NEQ "" (
set From="%~1"
set To="%~2"
set Subject="%~3"
set Body="%~4"
set SMTPServer="%~5"
set User="%~6"
set Pass="%~7"
set fileattach="%~8"
)
set "vbsfile=%temp%\email-bat.vbs"
del "%vbsfile%" 2>nul
set cdoSchema=http://schemas.microsoft.com/cdo/configuration
echo >>"%vbsfile%" Set objArgs = WScript.Arguments
echo >>"%vbsfile%" Set objEmail = CreateObject("CDO.Message")
echo >>"%vbsfile%" objEmail.From = %From%
echo >>"%vbsfile%" objEmail.To = %To%
echo >>"%vbsfile%" objEmail.Subject = %Subject%
echo >>"%vbsfile%" objEmail.Textbody = %body%
if exist %fileattach% echo >>"%vbsfile%" objEmail.AddAttachment %fileattach%
echo >>"%vbsfile%" with objEmail.Configuration.Fields
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendusing") = 2 ' not local, smtp
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpserver") = %SMTPServer%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpserverport") = %port%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpauthenticate") = 1 ' cdobasic
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendusername") = %user%
echo >>"%vbsfile%" .Item ("%cdoSchema%/sendpassword") = %pass%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpusessl") = %SSL%
echo >>"%vbsfile%" .Item ("%cdoSchema%/smtpconnectiontimeout") = 30
echo >>"%vbsfile%" .Update
echo >>"%vbsfile%" end with
echo >>"%vbsfile%" objEmail.Send
cscript.exe /nologo "%vbsfile%"
echo email sent (if variables were correct)
del "%vbsfile%" 2>nul
goto :EOF

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