Question

Using batch file to save files with date and time stamp

Asked by: mhorner0224

I am trying to create a text file using a batch file. I format the text file then open it for the user to make entries into. I want to save the file name as follows.

computername_InstallerName_Install_Log_Date_Time.txt

I have tried a number of ways and it seems to save it and while I may get the name to work when I go to open it it does not find it. Is that because it is always looking for the current time where my time does not match it?

Can this be done or am I trying to do the impossible?

I appreciate all suggestions.

Marcus

FOR %%i IN (C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO IF EXIST %%i:\Programs_R.here SET varDriveLetter=%%i:
:STEP1
	echo.
	echo.
	echo  Enter your name without a space in the middle.
	echo. Use this format: Marcus_Horner
	echo.
	echo.
	set /p installer=     What is your First and Last name?  
        echo.
        echo.
        set /p varGL=    What is this stores 4-digit GL# ?  
	cls
	echo.
	echo.
	@echo off
:MYVARIABLES
        SET varnewDate=%date%
	SET varnewTime=%time%
	set dude=%computername%_%installer%
	SET varroot=cd /d %varDriveLetter%\
	SET varpath=cd Installation_Files\Computer-Rx\Phase1\
	SET varPrograms= %varroot%Installation_Files\Computer-Rx\Phase1\Programs\
	SET varSaveFile="c:\Installation_Files\Logs\%dude%_Phase1_Log_%varnewDate%_%varnewTime%.txt""
	SET incident="c:\Installation_Files\Logs\%dude%_Phase1_Incident_Report.txt"
        SET varMailman= %varroot%Installation_Files\MailMan\
        SET varNOTsigned="c:\Installation_Files\Logs\%dude%_Phase1_Installer_Agreement_NOT_Signed.txt"
	SET varSigned="c:\Installation_Files\Logs\%dude%_Phase1_Agreement_Signed.txt"
 
:FILECREATION
:STEP2	
echo     ____________________________________________________________________
echo                         Automated Script written for 
echo               Computer-RX Installations by Marcus Horner 2009 
echo                         Server 2008 Image Preparation
echo     ____________________________________________________________________
echo.
	echo.
	IF exist %varSigned% GOTO AGREED
	cls
	echo.
	echo.
	echo  Welcome %installer%. I hope you are having a nice day.
	echo.
	echo.
	echo  This program is an installation and functions as the installer's 
	echo.
	echo  digital checklist for verifying they have installed and configured 
	echo.
	echo  the various tasks presented in the Server 2008 Image Preparation.
	echo.
	echo.
	echo  By agreeing to these terms you are signing off that you will have 
	echo.
	echo  completed all steps in this installation and verified them for accuracy.
	echo. 
	set /p agree= Do you agree to this? (Y) Yes  (N) No  
	echo.
        IF /i "%agree%" == "Y" GOTO AGREED
        IF /i "%agree%" == "N" GOTO DOESNOTAGREE
:DOESNOTAGREE:
        @echo off
        cls
        echo.
        echo.
        echo  Well %user% that is unfortuntate. Please explain why you refuse to
        echo  accept the installer's user agreement.
        echo.
        echo.
        echo  I will open a file for your to report your reasons.
        echo.
        echo.
        echo. When finished simply save and close the file.
        date /t >> %varNOTsigned%
        time /t >> %varNOTsigned%
        echo               USA Drug IT Department Digital Installation Form >> %varNOTsigned%
	echo. >> %varSaveFile%
        echo. >> %varNOTsigned%
	echo %installer% has chosen not to sign their digital signature for %computername% Phase 2 Server 2008 C-Rx Installation for the following reasons. >> %varNOTsigned%
        echo. >> %varNOTsigned%
        echo. >> %varNOTsigned%
        echo  Reasons... >> %varNOTsigned%
        echo. >> %varNOTsigned%
        notepad.exe %varNOTsigned%
	echo. >> %varNOTsigned%
        echo. >> %varNOTsigned%
        echo  Signed: %user%
	%varMailman%
        echo. >> %varNOTsigned%
	sendemail.exe -u "%dude% Phase 2 Installer Agreement Issue" -t "mhorner@usadrug.com" -f "%installer% <installer@usadrug.com>" -o message-file="%varNOTsigned%" -s "email.usadrug.local" -a "%varNOTsigned%"
        pause
	cls
        echo.
        echo.
        echo  This program will now close.
        @echo off
        ping 127.0.0.1 >>junk
        del junk
        exit

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-01 at 08:34:12ID24698348
Tags

batch file

,

command prompt

,

date

,

time

Topics

MS DOS

,

Windows Batch Scripting

Participating Experts
2
Points
500
Comments
12

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Mission: Impossible...
    WARNING: long question. Read completely before answering!... I have the following situation: In a folder are several files with transaction information. These are no database files, but special EDI files and related stuff, which require me to use a parser to read them in Del...
  2. BATCH FILE
    Hi Does anyone know how to fire a PHP script using a BATCH file? Thanks
  3. Batch File
    Hi... I'm trying to create a batch file that is supposed to check a directory for specific file extensions and then delete them or move them to a different folder. After that it is supposed to send a message to the administrator or send an email to the administrator. Is t...
  4. batch
    net localgroup Administrators AA /add net localgroup Administrators BB /add I need a batch script syntax that if the machines are test1,test1,test2 then don't run the script.
  5. Batch file if %computername% matches a certain string (…
    This should be an easy solution for you scripting masters. I have a batch script with a single line in it that runs an executable off a server. This is working fine. What I would like to do is make it so that it doesnt run on any of our server. All of our server have one of...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: t0t0Posted on 2009-09-01 at 09:00:10ID: 25232929

The elements you need are:

    %COMPUTERNAME%
    %USERNAME%
    %DATE%
    %TIME%

The first two are environment variables, the last two are dynamic variables.

The first two are straight forward however, we only need specific parts of %DATE% and %TIME%.

    SET InstallDate=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%

So, if your date is normally displayed as dd/mm/yyyy then the above line will set InstallDate to yyyymmdd.

    SET InstallTime=%TIME:~0,2%%TIME:~3,2%

This returns: hhmm %InstallTime% by extracting just the first two digits and 'minute' digits of the time (where the time format is usually hh:mm:ss.cc).


Putting this together then, you get:

    SET InstallDate=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
    SET InstallTime=%TIME:~0,2%%TIME:~3,2%
    SET FileName=%COMPUTERNAME%_%USERNAME%_%InstallDate%_%InstallTime%.txt

and %FileName% contains the correctly formatted filename eg:

    Computer01_Freddie_20090901_1658.txt


Hope that's helpful to you

 

by: mhorner0224Posted on 2009-09-01 at 10:00:07ID: 25233566

I am driving for the next five hours but as soon as I get a chance I will try this out. Thank you. Marcus

 

by: t0t0Posted on 2009-09-01 at 10:41:24ID: 25233936

Blimey! A 5 hour drive eh?....  Don't be rushing though.... I'm in the process of making some suggestions to your code so this in itself will take time.

 

by: mhorner0224Posted on 2009-09-01 at 12:03:52ID: 25234816

Yep. Headed to Starkville Mississippi. Thanks.

 

by: QlemoPosted on 2009-09-06 at 06:07:05ID: 25269654

Hi Marcus,

varSaveFile
is your only file with a date and time portion in it. But is only written once, and that is a empty line. On every other occasion you use varNOTSigned, which is a fixed name containing the username as variable part.
However, even if not intended, this should open a notepad with the "correct" file containing all the stuff you put in it. And then send it.

As t0t0 tried to tell you already, %date% and %time% cannot be used without transformation in filenames, as there are slashes and colons, which are not allowed as part of filenames.

I for myself prefer to use a construction of

(echo.
echo Line1
echo Line2
) > someFile.txt
over the echo. >> someFile.txt  method. But that is a matter of taste, and reduction of error sources thru mistyping.

Next, the lines
ping 127.0.0.1 >>junk
del junk
could be better written as (and I would prolong it to 5 seconds instead of 2)
ping 127.0.0.1 -n 6 >nul

 

by: mhorner0224Posted on 2009-09-06 at 09:21:15ID: 25270483

I have done as instructed and my date shows up as ...

MARCUS-MOBILE_Joe_Poe_Phase1_Installer_Agreement_NOT_Signed_20090609_1059.txt

So, it is putting the Year, then day, then the Month for the date portion. And when I go to send the file it finds it now. If you notice that the name portion has an underscore added to it. If I leave a blank space it can no longer find the file and saves the file into two files. So I have had to instruct the user to add the underscore  when typing in their name. Can anyone explain why this is or how I can get around it? I will add my code so you can see what I am doing.

I accept input for agreeing to the use of the file. It will accept either upper or lower case. Is there a way to change it to upper case?

Again, I appreciate your mentoring.

Regards,

Marcus

@echo off
TITLE Phase 1 Server 2008 - Image Preparation
COLOR 17
FOR %%i IN (C D E F G H I J K L M N O P Q R S T U V W X Y Z) DO IF EXIST %%i:\Programs_R.here SET varDriveLetter=%%i:
:STEP1
	echo.
	echo.
	echo  Enter your name without a space in the middle.
	echo. Use this format: Marcus_Horner
	echo.
	echo.
	set /p installer=     What is your First and Last name?  
        echo.
        echo.
        set /p varGL=    What is this stores 4-digit GL# ?  
	cls
	echo.
	echo.
	@echo off
:MYVARIABLES
	SET InstallDate=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
	SET InstallTime=%TIME:~0,2%%TIME:~3,2%
	set dude=%computername%_%installer%
	SET varroot=cd /d %varDriveLetter%\
	SET varpath=cd Installation_Files\Computer-Rx\Phase1\
	SET varPrograms= %varroot%Installation_Files\Computer-Rx\Phase1\Programs\
	SET varSaveFile="c:\Installation_Files\Logs\%dude%_Phase1_Log_%InstallDate%_%InstallTime%.txt"
	SET incident="c:\Installation_Files\Logs\%dude%_Phase1_Incident_Report_%InstallDate%_%InstallTime%.txt"
    SET varMailman= %varroot%Installation_Files\MailMan\
    SET varNOTsigned="c:\Installation_Files\Logs\%dude%_Phase1_Installer_Agreement_NOT_Signed_%InstallDate%_%InstallTime%.txt"
	SET varSigned="c:\Installation_Files\Logs\%dude%_Phase1_Agreement_Signed_%InstallDate%_%InstallTime%.txt"
	:: Checking for the Logs directory.
	IF exist "C:\Installation_Files\Logs" GOTO STEP2
	:: Didn't find it so now checking for the Installation_Files direcotry
	IF exist "C:\Installation_Files" GOTO MAKELOG
	:: Didn't find it so now making both directories
	md c:\Installation_Files\Logs 
	GOTO STEP2
 
:MAKELOG
	md c:\Installation_Files\Logs 
	GOTO STEP2
 
 
:STEP2	
echo     ____________________________________________________________________
echo                         Automated Script written for 
echo               Computer-RX Installations by Marcus Horner 2009 
echo                         Server 2008 Image Preparation
echo     ____________________________________________________________________
echo.
	echo.
	IF exist %varSigned% GOTO AGREED
	cls
	echo.
	echo.
	echo  Welcome %installer%. I hope you are having a nice day.
	echo.
	echo.
	echo  This program is an installation and functions as the installer's 
	echo.
	echo  digital checklist for verifying they have installed and configured 
	echo.
	echo  the various tasks presented in the Server 2008 Image Preparation.
	echo.
	echo.
	echo  By agreeing to these terms you are signing off that you will have 
	echo.
	echo  completed all steps in this installation and verified them for accuracy.
	echo. 
	set /p agree= Do you agree to this? (Y) Yes  (N) No  
	echo.
        IF /i "%agree%" == "Y" GOTO AGREED
        IF /i "%agree%" == "N" GOTO DOESNOTAGREE
:DOESNOTAGREE:
        @echo off
        cls
        echo.
        echo.
        echo  Well %user% that is unfortuntate. Please explain why you refuse to
        echo  accept the installer's user agreement.
        echo.
        echo.
        echo  I will open a file for your to report your reasons.
        echo.
        echo.
        echo. When finished simply save and close the file.
        date /t >> %varNOTsigned%
        time /t >> %varNOTsigned%
        echo               USA Drug IT Department Digital Installation Form >> %varNOTsigned%
	echo. >> %varSaveFile%
        echo. >> %varNOTsigned%
	echo %installer% has chosen not to sign their digital signature for %computername% Phase 2 Server 2008 C-Rx Installation for the following reasons. >> %varNOTsigned%
        echo. >> %varNOTsigned%
        echo. >> %varNOTsigned%
        echo  Reasons... >> %varNOTsigned%
        echo. >> %varNOTsigned%
        notepad.exe %varNOTsigned%
	echo. >> %varNOTsigned%
        echo. >> %varNOTsigned%
        echo  Signed: %user%
	%varMailman%
        echo. >> %varNOTsigned%
	sendemail.exe -u "%dude% Phase 2 Installer Agreement Issue" -t "mhorner@usadrug.com" -f "%installer% <installer@usadrug.com>" -o message-file="%varNOTsigned%" -s "email.usadrug.local" -a "%varNOTsigned%"
        pause
	cls
        echo.
        echo.
        echo  This program will now close.
        @echo off
        ping 127.0.0.1 -n 6 >nul
        exit
:AGREED        
	@echo off
	echo %installer% agreed to the installer agreement. >> %varSigned%
	date /t >> %varSaveFile%
	echo. >> %varSaveFile%
	time /t >> %varSaveFile%
	echo. >> %varSaveFile%
	echo               USA Drug IT Department Digital Installation Form >> %varSaveFile%
	echo. >> %varSaveFile%
	echo  %computername% Installer Agreement & Digital Signature >> %varSaveFile%
	echo. >> %varSaveFile%
	echo    %varSveFile%
	echo  %computername% was installed and configured by: %installer%. >> %varSaveFile%
	echo.
	echo.
	echo  1) %installer% read and agreed to the acknowledgement notification by pressing "%agree%". >> %varSaveFile%
	cls

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:

Select allOpen in new window

 

by: QlemoPosted on 2009-09-06 at 09:43:11ID: 25270568

You can create a underscore in the filename easily by using

set installer=%installer: =_%

so the users do not need to use underscores.
However, why the space is a problem is not obvious to me. You are using the quoted filename all way long, so there shouldn't be any issue with it ...

I see you did not adopt my echo redirection recommendation. Maybe you like that one more:

>> %varSaveFile% echo.
>> %varSaveFile% echo    Don't echo this at home!
>> %varSaveFile% echo.

It puts the file redirection into direct attention, and looks better (more schematic).

Regarding the "agree" part:
It has a flaw, because ANY answer but Y or y will result in "DoesNotAgree". It should only allow for a clear Y or N, IMHO. You could do that with this code:



REM ...
        :agreeLoop
        set /p agree= Do you agree to this? (Y) Yes  (N) No  
        echo.
        IF "%agree%" == "Y" GOTO AGREED
        IF "%agree%" == "N" GOTO DOESNOTAGREE
        GOTO agreeLoop
:DOESNOTAGREE:
        @echo off
REM ...

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

Select allOpen in new window

 

by: mhorner0224Posted on 2009-09-06 at 10:13:23ID: 25270670

Would you explain the set installer=%installer: =_%
How does it know to look for the space in this variable to put the underscore symbol?

I did not understand the echo redirection. Are you saying you can say... the following
echo. >> somefile.txt
echo This is the start of the file >> somefile.txt

by typing

>> somefile.txt echo.
>> somefile.txt This is the start of the file.

In other words just change my order around? If so I had no idea you could do that.

Your loop for the agree section. Is this how you can set it so that it will only accept input of one or the other? Since they don't enter a Y or a N they will just stay in a continuous loop. And here I was thinking there would be a lot of code for that. That's pretty simple.

One more thing I have been struggling with is to capture errors. From what I have read you will use "2>&1". I am currently using two echo statements. One to capture to a text file and one to display on the screen. Is there a way to combine the two into one statement? With what I have is this the proper way to write the code?

I am learning a lot and appreciate your time.

Marcus

Here is an example of how I envision using it.

Error capture code
 
@echo off
	%varroot%
	%varpath%
	cls
	echo.
	echo.
	IF exist "C:\Program Files\McAfee\" GOTO  AS400
	IF exist "C:\Program Files\Network Associates" GOTO AS400
	@echo off
	>> somefile.txt echo  Now installing McAffee Antivirus
	echo  Now installing McAffee Antivirus
	echo.
	echo  Install using the Perpetual License.
	2>&1 %varPrograms%
	2>&1 McAfee.exe
	>> %varSaveFile% echo  5) McAfee antivirus has been installed.
	GOTO AS4001
 
:DISHES
	@echo off
	
        >>somefile.txt 2>&1  net use s: \\Acquisitions\IT\CheckList
	IF exist "s:\%varGL%" GOTO COPYLOG
        >>somefile.txt 2>&1 md s:\%varGL%
	echo.
	echo.
	echo.
	::  Time to clean up the kitchen and do the dishes. 
	::  Deleting temporary files that we don't need anymore.
:COPYLOG
	>>somefile.txt 2>&1 copy %varSaveFile% s:\%varGL%
	>>somefile.txt 2>&1 cd %varDriveLetter%Installation_Files\Computer-Rx\Phase2\ 
	>>somefile.txt 2>&1 copy StartPhase2.bat "c:\Users\%username%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup"	
>>somefile.txt 2>&1 net use s: /delete /y
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:

Select allOpen in new window

 

by: t0t0Posted on 2009-09-06 at 11:48:17ID: 25271015

I was thinking of something more along these lines:


::========================================
:: Computer-RX Installations
::
:: Automated Script
::========================================
:main
   @echo off
   set spaces=[                            ]
   set spc16=%spaces:~1,16%
   set spc26=%spaces:~1,26%

   ::------------------------------
   :: GET DRIVE LETTER
   ::------------------------------
   set varDriveLetter=
   call :get_driveletter
   if not %errorlevel%==0 (
      call :display_titlescreen
      echo.
      echo %spc16%Cannot locate application
      echo.
      set /p .=%spc16%<nul
      pause
      cls
      exit /b 1
   )

   ::------------------------------
   :: GET INSTALLER
   ::------------------------------
   set varErrorCode=0
   :loop1
      call :display_titlescreen
      set varInstaller=
      call :get_installer %varErrorCode%
      call :validate_installer "%varInstaller%"
      set varErrorCode=%errorlevel%
   if %varErrorCode% gtr 0 goto loop1

   ::------------------------------
   :: Substitue space with underline
   ::------------------------------
   set varInstaller=%varInstaller: =_%

   ::------------------------------
   :: GET GL CODE
   ::------------------------------
   set varErrorCode=0
   :loop2
      call :display_titlescreen
      set varGL=
      call :get_glcode %varErrorCode%
      call :validate_glcode %varGL%
      set varErrorCode=%errorlevel%
   if %varErrorCode% gtr 0 goto loop2
   
   call :initialise_variables

   ::------------------------------
   :: GET AGREEMENT
   ::------------------------------
   :loop3
      call :display_titlescreen
      call :display_agreement
     
      echo.
      set varAgree=
      set /p varAgree=%spc26%Do you agree to this [Y/N]:
     
      if not defined varAgree goto loop3
   
      if /i "%varAgree%"=="y" (
         goto agreed
      ) else (
         if /i "%varAgree%"=="n" (
            goto disagreed
         ) else (
            goto loop3
         )
      )
   
   :: Some more code may go here
   :: Some more code may go here
   
   ::------------------------------
   :: END PROGRAM
   ::------------------------------
   call display_titlescreen
   echo %spc16%Thank you.
   echo.
   pause
   cls
exit /b



::========================================
:: DISPLAY TITLE SCREEN
::========================================
:display_titlescreen
   cls
   echo.
   echo      _____________________________________________________________________
   echo.
   echo                          Automated Script written for
   echo                 Computer-RX Installations by Marcus Horner 2009
   echo                          Server 2008 Image Preparation
   echo      _____________________________________________________________________
   echo.
   echo.
      echo.
      echo.
   echo.
   echo.
exit /b 0



::========================================
:: GET DRIVE LETTER
::========================================
:get_driveletter
      set varPrograms=Installation_Files\Computer-Rx\Phase1\Programs
   set varDriveLetter=
   for %%a in (C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
      if exist "%%a:\%varPrograms%\" set varDriveLetter=%%a:
   )
   if not defined varDriveLetter exit /b 0
exit /b 0



::========================================
:: GET INSTALLER
::========================================
:get_installer
   if %1==0 (
      echo.
   ) else (
      if %1==1 (
         echo %spc16%ERROR: You must enter your name...
      ) else (
         if %1==2 (
            echo %spc16%ERROR: Name contains Invalid characters...
         ) else (
            if %1==3 (
               echo %spc16%ERROR: Invalid name...
            )
         )
      )
   )
   
   echo.
   echo.
   echo.
   set /p varInstaller=%spc16%Please enter your name:
exit /b 0



::========================================
:: GET GL CODE
::========================================
:get_glcode
   if %1==0 (
      echo.
   ) else (
      if %1==4 (
         echo %spc16%ERROR: You must enter a GL code...
      ) else (
         if %1==5 (
            echo %spc16%ERROR: Invalid GL code...
         ) else (
            if %1==6 (
               echo %spc16%ERROR: Not enough digits...
            ) else (
               if %1==7 (
                  echo %spc16%ERROR: Too many digits...
               )
            )
         )
      )
   )

   echo.
   echo.
   echo.
   echo %spc16%Please enter your name: %varInstaller%
   echo.
   echo.
   set /p varGL=%spc16%Please enter your store's 4-digit GL code:
exit /b 0



::========================================
:: DISPLAY AGREEMENT
::========================================
:display_agreement
      echo      Welcome %varInstaller%. I hope you are having a nice day.
      echo.
      echo.
      echo      This program is an installation and functions as the installer's
      echo.
      echo      digital checklist for verifying they have installed and configured
      echo.
      echo      the various tasks presented in the Server 2008 Image Preparation.
      echo.
      echo.
      echo      By agreeing to these terms you are signing off that you will have
      echo.
      echo      completed and verified the accuracy of all steps in this installation.
      echo.
   echo.
exit /b 0



::========================================
:: AGREED
::========================================
:agreed
   call :display_titlescreen
   echo %spc16%Unfinished section...
   echo.
   echo %spc16%[%varInstaller%]
   echo.
   echo %spc16%[%varGL%]
   echo.
   echo %spc16%[%varAgree%]
   echo.
   set /p .=%spc16%<nul
   pause
exit /b
   

   
::========================================
:: DISAGREED
::========================================
:disagreed
   rem set varNOTsigned="c:\Installation_Files\Logs\%dude%_Phase1_Installer_Agreement_NOT_Signed.txt"
   rem set varNOTsignedTemp="c:\Installation_Files\Logs\%dude%_Phase1_Installer_Agreement_NOT_Signed.tmp"

   set varNOTsigned="%temp%\%dude%_Phase1_Installer_Agreement_NOT_Signed.txt"
   set varNOTsignedTemp="%temp%\%dude%_Phase1_Installer_Agreement_NOT_Signed.tmp"
   
   call :display_titlescreen
   echo      Well %varInstaller% that is unfortuntate. Please explain why you refuse to
   echo      accept the installer's user agreement.
   echo.
   echo.
   echo      I will open a file for your to report your reasons.
   echo.
   echo.
   echo.     When finished simply save and close the file.
   echo.
   set /p .=     <nul
   pause
   
   (:redirect
      echo My reason for not accepting the installers user agreement is:
      echo.
      echo.
      echo.
   )>%varNOTsignedTemp%
   
   notepad %varNOTsignedTemp%
   
   (:redirect
      echo USA Drug IT Department Digital Installation Form for Store: %varGL%
      echo.
      echo Local Date: %date%
      echo Local Time: %time%
      echo.
      echo Installer:  %varInstaller%
      echo Computer:   %computername%
      echo.
     
      echo %varInstaller% has chosen not to sign their digital signature for %computername% Phase 2 Server 2008 C-Rx Installation for the following reasons:
      echo.
      echo.
      echo  Reasons...
      echo.
   )>%varNOTsigned%
   
   copy %varNOTsigned% + %varNOTsignedTemp% %varNOTsignedTemp% >nul
   move %varNOTsignedTemp% %varNOTsigned%
   
      (::redirect
      echo.
      echo.
      echo  Signed:
   )>>%varNOTsigned%

   pushd %cd%
   cd "%varDriveLetter%\Installation_Files\MailMan\"
      sendemail.exe -u "Phase 2 Installer Agreement Issue" -t "mhorner@usadrug.com" -f "%varInstaller% <installer@usadrug.com>" -o message-file="%varNOTsigned%" -s "email.usadrug.local" -a "%varNOTsigned%"
   popd
   set /p .=     <nul
   pause

      call :display_titlescreen
   echo %spc16%This program will now close.
   echo.
   set /p .=%spc16%<nul
   pause
   cls
exit /b



::========================================
:: VALIDATE INSTALLER
::========================================
:validate_installer
   setlocal enabledelayedexpansion

   set varErrorCode=0
   set varInstaller=%~1
   
   ::------------------------------
   :: If blank, exit with code 1
   ::------------------------------
   if not defined varInstaller exit /b 1

   ::------------------------------
   :: Save name to file & Get length of name -1
   ::------------------------------
   echo %varInstaller%>len
   for %%a in (len) do set /a len=%%~za - 3

   ::------------------------------
   :: Check name is alpha and space
   ::------------------------------
   for /l %%l in (0,1,%len%) do (
      set character=!varInstaller:~%%a,1!
     
      if /i not "!character!" equ " " (
         if /i "!character!" lss "a" set varErrorCode=2  
         if /i "!character!" gtr "z" if /i "!character!" lss "A" set varErrorCode=2
         if /i "!character!" gtr "Z" set varErrorCode=2
      )
   )

   if %varErrorCode%==2 exit /b 2

   ::------------------------------
   :: Search for valid employee name - DISABLED
   ::------------------------------
   :: findstr "\<%varInstaller%\>" installers.txt >nul
   :: if not %errorlevel%==0 exit /b 3
exit /b 0

   
   
::========================================
:: VALIDATE GL CODE
::========================================
:validate_glcode
   set varErrorCode=0
   set varGL=%~1
   
   if not defined varGL exit /b 4

   ::------------------------------
   :: Check length is 4
   ::------------------------------
   echo %varGL%>len
   for %%a in (len) do set /a len=%%~za-2
   if %len% lss 4 exit /b 6
   if %len% gtr 4 exit /b 7
   
   ::------------------------------
   :: Search for GL code - DISABLED
   ::------------------------------   findstr "\<%varGL%\>" glcodes.txt >nul
   :: if not %errorlevel%==0 exit /b 5
exit /b 0

 

by: t0t0Posted on 2009-09-06 at 11:51:49ID: 25271028

But much more work needs doing to it.... so I abandoned it.....

 

by: QlemoPosted on 2009-09-06 at 11:54:20ID: 25271036

Would you explain the set installer=%installer: =_%
How does it know to look for the space in this variable to put the underscore symbol?
This is a special constrution for string replace: %var:search=replace% searches for  search and replaces it by replace. In this case, we search for a space, and replace it by a underscore. Any space will be replaced.

ad echo redirection: Yes, that works that way round. In this case, it is useful, in most other cases it obstructs the command or needs additional brackets around the command line (e.g. with IF, FOR). You can have a look at my article about special syntax and its pros and cons (search for "article dos pitfalls" to find it).

ad agree section: Yes, only an uppercase Y and N are accepted. It is that simple indeed.


2>&1 %varPrograms%
does not make sense, but isn't wrong on the other side. StdErr is normally your console, so you need not to redirect it as long as you do not redirect stdout. Short: 2>&1 makes sense if used in conjunction with >.
And there is no easy method to log something to both a file and the console. There are tools out there called like tee, one of them is mtee (http://www.commandline.co.uk/mtee/). There are an offspring / port of the UNIX tool tee, and allow for redirection and logging:

dir | mtee file.log
will output the results of dir both into file.log and the console.



 

by: mhorner0224Posted on 2009-09-06 at 12:13:48ID: 31623081

Thank you all. Holy smokes t0t0! I see you've done this a time or two. I will have to research everything you are doing in your example and see what I can understand. My initial questions are answered but now you've brought up new ones. I will look at your examples and see what I can pick-up on. I may post another series of questions for clarificaiton. I have learned a lot from this thank you.

Regards,

Marcus

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...