Microsoft DOS

13K

Solutions

12K

Contributors

Microsoft Disk Operating System (MS-DOS) was an operating system for x86-based personal computers, and traces of it are still found in the Windows operating system. DOS is still used in some embedded systems and for certain legacy 16-bit networks.

Share tech news, updates, or what's on your mind.

Sign up to Post

Introduction:
Recently, I got a requirement to zip all files individually with batch file script in Windows OS. I don't know much about scripting, but I searched Google and found a lot of examples and websites to complete my task. Finally, I was able to create the below script to complete my task. I have modified the original script as per my requirement & give credit to the creator of this script ( Anonymous ).

For Original script click here...
 
Below is the modified script:
@echo off

Title autozip.bat

REM updated 30/07/2015
REM created by: Anonymous
REM modified by: Yashwant Vishwakarma

REM This script compresses files in a folder Note: files with the same name 
REM but with different extensions will be in the same archive.

path=%path%;"c:\program files\winrar"

REM ****************** Folder to compress******************
set dir=C:\testzip
REM *******************************************************

REM change to directory
cd %dir%

echo Folder to compress in *.RAR format:
echo %dir%

echo Compressing files started....

REM Compress files in directory individually without subdirectories

echo.
FOR %%i IN (*.*) do (
rar a "%%~ni" "%%i"
)
goto eof

Open in new window

For more commands and syntax follow winrar command line help online

In the original batch file script, there were 7 options which required manual intervention to choose and perform tasks. However, I want to completely automate this task so I modified it and its working absolutely fine for me.

Coding Explanation:
Table.pngReferences: 

Conclusion:
This is what I did with a given script, so I wanted to share my learning and experience with you. I hope it will help someone also when this type of requirement will come.

Keep smiling, rising, shining & stay blessed.
                                                                 forefinger-down-512.png****Kindly vote this if you liked this article by clicking on the 'Vote' button & leave your precious comment !!! *****
 
7
 
LVL 7

Author Comment

by:Yashwant Vishwakarma
Comment Utility
Thank You bfuchs :)
Have a great day ahead :)
Keep smiling n shining always :)
Stay blessed :)
0
Microsoft Certification Exam 74-409
LVL 1
Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Being a system administrator some time we require to do things remotely, one of them is installing software. Here I am going to tell you how to install software through wmic (Windows management instrument console). I am not at all saying that this is the only way to perform such activities but as I am fond of writing scripts and love to do work remotely without disturbing the users {and most importantly it is easy} so here is my way of installing software via script

Prerequisites

Administrative privileges on the system on which you want to install the software
WMIC (Windows Management Instrumentation Console)
Text Editor (NotePad, WordPad etc)
Xcopy(for copying installation files into the system)
MSI (Microsoft software installer file of desired software)

Code:

@EchO off
SET /P tsystem=Enter Target system:
EchO.
XCopy "\\Source Path\*.*" "\\%tsystem%\target path\*.*" /E /C /H /R /Y
WMIC /Node:"%tsystem%" product call install true,"","Target Path\MSI file"
RD /S /Q "\\%tsystem%\d$\Folder name"

Explanation:

Open a text editor e.g notepad and type the above code. Firstly set a variable named “tsystem” which will store the target system name on which you want to install the software. Now copy all the installation files of the software in the target system with XCOPY command.
XCopy "\\Source Path\*.*" "\\%tsystem%\target path\*.*" /E /C /H /R /Y …
0
YESTERDAY

YESTERDAY.BAT is inspired by a previous article I wrote entitled: TOMORROW.BAT.

The crux of this batch file revolves around the XCOPY command - a technique I discovered while looking for an easy method for validating dates avoiding complex maths. Here's the whole thing:

::================================================
:: YESTERDAY.BAT
::
:: Function to return yesterday's date
::================================================
@echo off

set /a d=%date:~0,2%
set /a m=%date:~3,2%
set /a y=%date:~6,4%

:loop
  set /a d-=1

  if %d% lss 1 (
    set d=31
    set /a m-=1

    if %m% lss 1 (
      set m=12
      set /a y-=1
    )
  )
xcopy /d:%m%-%d%-%y% /l . .. >nul 2>&1 || goto loop

echo %d%/%m%/%y%

Open in new window


INPUT
The code receives input from the system's %DATE% whose format is DD/MM/YYYY.

set /a d=%date:~0,2%
set /a m=%date:~3,2%
set /a y=%date:~6,4%

Open in new window

If your system's date format differs from DD/MM/YYYY then you will need to edit these three lines or provide some other method of delivering the date to the batch file in order for the rest of the code to work correctly.

You are reminded: This is an advanced topic and therefore, you are expect to know how to do that.
Use arithmetic 'SET /A' instead of 'SET' because 'SET /A' drops any leading zeros (a major problem due to the ambiguity between octal, decimal and hexadecimal '08' and '09') or spaces.


DECREMENTING DAY
'1' is deducted from the current day (day) value. If the resultant date is valid, it is returned to the user.  

For the most part, the loop will execute just once. If the current day is the first day of the month and if there are 30 days in the previous month, the loop will execute twice.  In the worst-case scenario, where the current day is March 1st and where February 28th falls on a non-leap year, the loop will execute four times.


Open in new window

0
VALIDATING DATES

One method of validating dates is to jam the date into the DATE command and see if it accepts it by examining the system's errorlevel value. A non-zero result indicates failure. A typical example might look something like the following:

echo.|date %d%/%m%/%y% >nul
if %errorlevel% gtr 0 ... etc.
The problem with this approach is it changes the system's global date setting and this can be risky in a multitasking environment. Even if the current date were to be preserved in temporary variable and then restored afterwads as in the following exmaple, the possibility of a midnight rollover cannot be ignored as this would throw the system's date out by a whole day or so.

set current_date=%date%
echo.|date %d%/%m%/%y% >nul
if %errorlevel% gtr 0 ... etc.
date %current_date%
The solution is to use the XCOPY command. This takes the following format:

XCOPY /D:m-d-y /L "source" "destination" >NUL 2>&1
For XCOPY to do it's job properly, all of its command line parameters and switches must be in good order because the technique described in this article relies on XCOPY's error condition to determine whether the date in '/D:m-d-y' is valid or not. This error must therefore come from 'm-d-y' alone and no other parameter. Moreover, all output is redirected to the NUL device hence the '>nul 2&>1' so errors will be difficult to detect - both syntactical and logical.

The parameters for XCOPY are:

/D:<date in m-d-y format>
/L
<source>
<destination
4
TOMORROW

TOMORROW.BAT is inspired by a question I get asked over and over again; that is, "How can I use batch file commands to obtain tomorrow's date?"

The crux of this batch file revolves around the XCOPY command - a technique I discovered while looking for an easy method for validating dates that avoids a series of complex mathematical procedures.  Here's the complete batch file:
::================================================
:: TOMORROW.BAT
::
:: Function to return tomorrow's date
::================================================
@echo off

set /a d=%date:~0,2%
set /a m=%date:~3,2%
set /a y=%date:~6,4%

:loop
  set /a d+=1

  if %d% gtr 31 (
    set d=1
    set /a m+=1
     
    if %m% gtr 12 (
      set m=1
      set /a y+=1
    )
  )
xcopy /d:%m%-%d%-%y% /l . .. >nul 2>&1 || goto loop

echo %d%/%m%/%y%

Open in new window



INPUT
The input section is pretty straightforward.  The code receives input from the system's %DATE% whose format is DD/MM/YYYY.

set /a d=%date:~0,2%
set /a m=%date:~3,2%
set /a y=%date:~6,4%

Open in new window

If your system's date format differs from DD/MM/YYYY then you will need to edit these three lines or provide some other method of delivering the date to the batch file in order for the rest of the code to work correctly.

You are reminded: This is an advanced topic and therefore, I would expect you to know how to do that.
When assigning values to variables, we use using SET /A (rather than just SET) to overcome the problem of attempting to perform octal arithmetic on '08' and '09' later on. This is because leading zeros are trimmed off during arithmetic assignment.


INCREMENTING DAY
Incrementing the day itself is a doddle.  Basically, '1' is added to the current day value. If the resultant date is valid, it is returned to the user.  

The trick is in the end-of-month handling.  The majority of times, the loop will execute just the once.  If today is the last day in the month
6
 
LVL 43

Expert Comment

by:Steve Knight
Comment Utility
Hadn't seen this one before Paul... could come in useful!

Steve
0
 
LVL 11

Author Comment

by:paultomasi
Comment Utility
Steve

I'm currently doing another write-up (like the many in the making). I see it's strength in validating dates input by the user.
0
One of my most closely kept secrets is revealed in this discussion

How to output text on the same line


This question was recently posted in EE by Simon336697

Consider the problem:

ECHO Hello
ECHO World

Open in new window


This would output the following to the screen:

    Hello
    World

However, what if we wanted the words Hello and World to appear on the same line as in:

    Hello World

This could be done as follows:

ECHO Hello World

Open in new window


But this discussion is not about that. This discussion explores the possibility of outputting text to the previous line.


Now consider the following:

    output text to screen
    process other commands
    output more text to the same line

Impossible? Read on....


Firstly, let's use Simon336697's question as an example:

    1)  output "Searching...." to screen
    2)  PING
    3)  output (append) result to the same line

Before we continue, let's refine these instructions:

 1   )  output "Searching for %Computer%.... " to screen
 2   )  PING %Computer% >NUL 2>&1
 3.1)  if ping fails...
 3.2)     output "FAIL" to previous line
 3.3)  otherwise...
 3,4)     output "SUCCESS" to previous line
 3.5)  end-if

[step=""][Ed Note]: The 2>&1 portion simply redirects STDERR to STDOUT.  
Thus, the sequence >NULL 2>&1 totally silences the PING command.[/step]
And, this is what the code would look like in a DOS batch file:


Open in new window

16
 
LVL 43

Expert Comment

by:Steve Knight
Comment Utility
I have used this method too in the past to make it more obvious (ish):

SET PRINT=^<NUL set /p =

Then in the area needed you can do:

%PRINT% What I want to print

or

SET echox=^<NUL set /p =
%echox% mytext

etc.

Steve
0
 
LVL 70

Expert Comment

by:Qlemo
Comment Utility
Just to throw in another variant:
doskey echox=^<nul set /p=$*

Open in new window

and you can use echox everywhere in the current shell. Looks better than %echox%, IMO.
0
Using dates in 'DOS' batch files has always been tricky as it has no built in ways of extracting date information.  There are many tricks using string manipulation to pull out parts of the %date% variable or output of the date /t command but these rely heavily on the regional settings of the user the script is running as.

If a quick and dirty date or time stamp for a filename, for instance, is required you can use some simple character substitution to amend the date / time entries to remove the / and : characters so that they can be used in a filename, e.g.

set filename="File %date:/=-%%time::=-%".txt

Open in new window

results in a filename like  "File 09-07-2009 9-37-42.40.txt"
or "File Thu 09-07-2009 9-37-42.40.txt"
or "File Thu 07-09-2009 9-37-42.40.txt"
or "File 07-09-2009 9-37-42.40.txt"
etc.
which is why extracting strings from a date is unreliable.

VBScript can be be used to extract day names, parts of the date etc. and combined into a batch file by using a for command to read the data ouput by a VB Script (amongst other ways).  This simple one line VBscript for instance returns all the various parts of a date that may be needed and can be used as in the example to construct a filename / path for instance:

wscript.echo weekdayname(weekday(date)) & "," & weekday(date) & "," & weekdayname(weekday(date),true) & "," & day(date) & "," & month(date) & "," & year(date) & "," & monthname(month(date),false) &"," & monthname(month(date),true) 

Open in new window


That could be called dateparts.vbs and stored somewhere for running or constructed on the fly from the batch file, e.g. in the user's temp folder.  All that is needed is to escape the & characters with a ^ and use redirection (>) to create a temporary VBS file:


Open in new window

13
 
LVL 43

Author Comment

by:Steve Knight
Comment Utility
End of Last month:

@echo off
REM Use VBScript to get date.  This will get the first day of this month and take one off to get last day of last month
(echo eolm=dateserial^(year^(date^),month^(date^),1^)-1
echo wscript.echo year^(eolm^) ^& right^(100 + month^(eolm^),2^) ^& right^(100+day^(eolm^),2^)) > "%temp%\dateparts.vbs"
for /f "tokens=1 delims=" %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set yyyymmdd=%%a


echo End of last month to use in filename was %yyyymmdd%

pause

Open in new window

eolm.cmd
0
 
LVL 56

Expert Comment

by:Bill Prew
Comment Utility
And of course, one of my preferred choices for date time formatting and math is DOFF, check it out at the link below.  It is a small utility program that you would need to have available to your BAT scripts, but I just keep a copy in a "util" folder that I include in my PATH.  Makes things very easy after that:

for /f "tokens=*" %%A in ('doff _yyyymmdd_hhmiss') do set dt=%%A

Open in new window


To get yesterday date you can simply do:

for /f "tokens=*" %%A in ('doff _yyyymmdd_hhmiss -1d') do set dt=%%A

Open in new window



Link:

http://www.jfitz.com/dos/#DOFF

***** EDIT *****

Whoops, looks like the creator of that handy freeware utility let the domain go.  You can still access the prior content of that page to see a description at the Internet Wayback Machine project via the first link below, and download the utility itself via the second link below.

http://web.archive.org/web/20150912034516/www.jfitz.com/dos/index.html
http://web.archive.org/web/20150912034516/www.jfitz.com/dos/doff10.zip



»bp
0
Mouse Trap
The following is a collection of cases for strange behaviour when using advanced techniques in DOS batch files. You should have some basic experience in batch "programming", as I'm assuming some knowledge and not further explain the basics. For some basics I will create a tutorial to be published here very soon (reference will be posted here).

It's an Interpreter
If using complex mechanisms like subshelling (using commands enclosed in round brackets), keep in mind batch files are not really like using a programming language - batch language isn't that accurate, there are several flaws in the interpreter we have to take care of.

As  cmd.exe  being an interpreter, it reads line after line, and does some pattern replacing in advance to executing the line.
A "line" can be
* a single physical line
* several physical lines connected by a caret (^) at the end of each line
* several physical lines enclosed in round brackets

A single line is hence:
 
@echo off

Open in new window


if 1 == 1 (echo yes) else (echo no)

Open in new window


echo Writing a long ^
text here

Open in new window


if 1 == 1 (
  echo yes
) else (
  echo no
)

Open in new window

Why should one know? As said already, it's an interpreter we use, and it's applying some string replacements.
If you are using environment variables, which is one of the things you will use every time, this gets most important.
E.g. the following code will not work as expected:
 
set example=1
if %example% == 1 (
  set example=2
  echo %example%
)
REM result:   1
REM expected: 2

Open in new window

In the first line, variable  example  is set to 1. In the next "line", containing  IF  up to the closing bracket, each occurance of  %example%
20
 
LVL 70

Author Comment

by:Qlemo
Comment Utility
Thanks, footech. I have introduced a new line 2 now, so the reference is correct ;-).
0
 
LVL 11

Expert Comment

by:loftyworm
Comment Utility
very nice, going in my DOS batch links library!
0

Microsoft DOS

13K

Solutions

12K

Contributors

Microsoft Disk Operating System (MS-DOS) was an operating system for x86-based personal computers, and traces of it are still found in the Windows operating system. DOS is still used in some embedded systems and for certain legacy 16-bit networks.