Windows Batch

12K

Solutions

11K

Contributors

Batch files are text files containing a script of commands that are executed by the command interpreter on DOS, OS/2 and Windows systems. Most commonly, they are used to perform a series of functions that are repeated -- copying a set of files created daily with one step, for example.

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

Sign up to Post

Example Running Script Auto Restarts as Elevated
This is a simple method I use to have a script run in a non-admin cmd prompt relaunch itself in an admin cmd prompt. No more manual intervention! This is a simple function you can add to to the top of any CMD script and call to do the needful.
1
Learn SQL Server Core 2016
LVL 13
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

Remove Software Remotely
This article will show you how you can remove software remotely with the use of PsTools, and how to remotely install another one.
0
This is a fine trick which I've found useful many times, when you just don't want to accidentally run a batch script or the commands needs administrator rights.
0
GetTickCount64
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve that problem by using the GetTickCount64 function.
3
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and will then append that to the file name.
0

Expert Comment

by:Mmavr Mmavr
Thank you very much.
Great Script.
Thank you
1

Expert Comment

by:guru prasad
I got error, Incorrect syntax as my database name has 'ver1.0', then i gave databae name [dbversion1.0], then error resolved. Thanks for the post. keep it up.
0
GraphicsMagick
This article shows how to convert a multi-page PDF file into multiple image files, with one image file created for each page of the PDF. It does this by utilizing an excellent, free software package called GraphicsMagick. The solution is amazingly simple — a single line of code!
6
LVL 67

Author Comment

by:Joe Winograd
Hi Miguel,

> although free

A crucial factor for some folks. Acrobat is expensive software — not everyone can afford it. You'll notice in the original question here at EE that inspired this article, the asker said, "If anyone has another free option, let me know."

> what's the use of an external solution doing something which is already part of the original software - Acrobat

Acrobat is also "external" in the sense that it is not part of Windows. For many users, Acrobat is not part of their "original software".

> "Export / (choose which type)" or "Save as/Save as type (choose which)"?

For one file (or a small number of files), this is fine. But many users have hundreds, even thousands, of files on which to operate. In that case, the manual Export or Save As is not the ticket. If you have Acrobat, the Action Wizard will work in some cases, but sometimes the better solution, imo, is a command line tool like gm.exe that can be called from a batch file, program, or script. I have written many programs that call gm.exe to operate on all files in a folder and, often, to recurse into subfolders to an unlimited depth, processing all files along the way. Also, you have a lot more control over the output files, with a fantastic set of options. Acrobat is a fine product (I have both Standard and Professional), but in many situations, I prefer writing a program that calls GraphicsMagick, as well as other software that supports a command line interface, such as Nuance's Power PDF — my EE article, Batch Conversion of PDF, TIFF, and Other Image Formats via Command Line Interface to PDF, PDF Searchable, and TIFF, discusses a good example of that. Regards, Joe
0

I. Introduction


There's an interesting discussion going on now in an Experts Exchange Group — Attachments with no extension. This reminded me of questions that come up here at EE along the lines of, "How can I tell the type of file from its contents?", as well as, "What kind of file has the XXX extension?" Writing an article to address this has been on my to-do list for a long time — the group discussion has inspired me to do it.


II. Determine the type of file from its XXX extension


Here are five links that can help in determining what an XXX file is:


http://extension.nirsoft.net/XXX

https://www.file-extensions.org/XXX-file-extension

http://www.fileinfo.com/extension/XXX

http://filext.com/file-extension/XXX

http://www.solvusoft.com/en/file-extensions/file-extension-XXX


Simply replace XXX with the file extension of interest. For example,


http://extension.nirsoft.net/TIFF

https://www.file-extensions.org/docx-file-extension

http://www.fileinfo.com/extension/AHK

http://filext.com/file-extension/xhtml

http://www.solvusoft.com/en/file-extensions/file-extension-opd


III. Determine the type of file from its contents


Now to the trickier question! An excellent file identifier application called TrID analyzes the contents of a file in an attempt to figure out what type of file it is. It comes in both a command line interface (CLI) version (for Windows and Linux) and a Graphical User Interface (GUI) version (Windows only) called TrIDNet. The downloads are at the links in the preceding sentence.


Both the CLI and GUI versions require a database/library of file definitions. This is a key feature of TrID and TrIDNet — the always increasing list of files that it recognizes. As of this article's submission date, the database contains 6,019 definitions (dated 13-August-2015). Note that there are separate downloads for the CLI definitions and the GUI definitions.


IV. More about TrID — the CLI version


After downloading the CLI version and its definitions, simply unpack the ZIP file with the program (trid.exe) and copy the definitions file (triddefs.trd) into the same folder as the program file. As mentioned above, using a database of definitions for file types is a really nice feature of TrID. Since file types are frequently added, the program author makes the definitions database available as a separate download, so you may go back to the website occasionally to get the latest definitions file.


Here's the syntax of the CLI version (v2.20):

 

Usage: TrID <[path]filespec(s)...> [-ae|-ce] [-d:file] [-ns] [-n:nn]
                                                                           [-@] [-v] [-w] [-?]
                                        
                                        Where: <filespec> Files to identify/analyze
                                               -ae        Add guessed extension to filename
                                               -ce        Change filename extension
                                               -d:file    Use the specified defs package
                                               -ns        Disable unique strings check
                                               -n:nn      Number of matches to show (default: 5)
                                               -@         Read file list from stdin
                                               -v         Verbose mode - display def name, author, etc.
                                               -w         Wait for a key before exiting
                                               -?         This help!


The program is free for personal use. Here's exactly what the license says (I took the liberty of correcting typos in it):


The program can be freely distributed and is freeware for non-commercial, personal, research and educational use. Contact the author for commercial use or commercialization of TrID or TrID's definitions and contained information.

I don't want to put the author's email address in this article, but you may find it in the Readme file that is part of the download.


V. More about TrIDNet — the GUI version


As stated earlier, the definitions for the GUI version are in a different format from the definitions for the command line version. The GUI definitions are in a large number of XML files, one for each file type — currently, 6,019 of them!


As with the CLI version, there's no installation needed — just unpack the ZIP file with the program (TrIDNet.exe) and copy the definitions (all of the XML files) into the same folder as the program file.


When running TrIDNet, here's the opening screen:


TrIDNet-opening-screen.jpg

V. Conclusion


To come full circle to the group discussion that prompted this article, I fed to both TrID and TrIDNet a file that has 40 characters in the file name but no file extension. Here's the TrID command line with its result (via copy/paste from the command prompt window):


trid "d:\0tempd\40 character file name without extension"


TrID/32 - File Identifier v2.20 - (C) 2003-15 By M.Pontello

Definitions found:  6019

Analyzing...


Collecting data from file: d:\0tempd\40 character file name without extension

100.0% (.PDF) Adobe Portable Document Format (5000/1)


Here's the TrID GUI result:



TrIDNet-sample-analyze.jpg

Both TrID and TrIDNet easily determined that it is a PDF file — and with 100% certainty. Of course, 100% certainty is not always the case, as shown in this real-life example of a file uploaded in a recent EE question. The file bumped into the 40-character file name limit and wound up with a .x file extension. Here are the TrID results on it:


TrID/32 - File Identifier v2.20 - (C) 2003-15 By M.Pontello

Definitions found:  6019

Analyzing...


Collecting data from file: d:\0tempD\Time-Interval-Frequency-calculationv51.x

 51.3% (.XLSM) Excel Microsoft Office Open XML Format document (with Macro) (57500/1/12)

 45.0% (.XLSX) Excel Microsoft Office Open XML Format document (50500/1/11)

  3.5% (.ZIP) ZIP compressed archive (4000/1)


It is, in fact, a .XLSM file, as predicted by TrID, although with only 51.3% certainty. After changing the file type from .x to .xlsm, it loaded perfectly into Excel.


If you find this article to be helpful, please click the thumbs-up icon below. This lets me know what is valuable for EE members and provides direction for future articles. Thanks very much! Regards, Joe

17
LVL 67

Author Comment

by:Joe Winograd
Hi Bill,
Thanks for the kind words and the upvote — much appreciated! I like your "Dealing With Unknown Files and File Extensions" title — it's better than the one I chose. Regards, Joe
0
LVL 36

Expert Comment

by:Duncan Roe
The Linux file command gets the file type right every time (file extensions are a Windows thing I guess)
0
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 8

Author Comment

by:Yashwant Vishwakarma
Thank You bfuchs :)
Have a great day ahead :)
Keep smiling n shining always :)
Stay blessed :)
0
In a previous article here at Experts Exchange, I presented a solution to the question of creating a multi-page PDF file containing contact sheets (aka a montage of thumbnails) for all JPG files in a folder. A recent question here at EE asked for a solution, in essence, to the reverse problem, that is, creating a JPG (or PNG) from a multi-page PDF file. In this case, the solution requires all pages of the PDF to be incorporated into a single image. At the question, I posted a relatively brief solution that uses the same GraphicsMagick software and approach as discussed in the article referred to above. Then I decided to write this new article with a more comprehensive explanation of the solution, including some interesting options.

The method presented here also requires the GraphicsMagick software. Another EE article explains how to download and install it. With GraphicsMagick installed, we're ready to proceed with the solution, which is amazingly simple — one line of code in a command prompt! Here it is:
 
gm.exe montage input.pdf output.jpg

Open in new window


Below is the resulting JPG from the command above using the six-page input.pdf file attached to this article:

output.jpg
As you can see, the default is to place the multiple pages of the PDF horizontally in the output image. If you prefer a different placement, use the -tile option, which is in the format of columns-by-rows. For example, here's the command to place them 3x2:
 
gm.exe montage -tile 3x2 input.pdf output.jpg

Open in new window


Below is the resulting JPG from the command above:

output-3x2.jpg
1
This article provides the solution to a question posed here at Experts Exchange. The asker of the question has many JPG images in many folders, and all of the folders are subfolders of one root folder. For each folder, the asker wants to create a PDF file containing thumbnail images (sized to 240 pixels wide) of every JPG in that folder. This is commonly known as a contact sheet or montage.

Let's begin the article with an illustration showing the results of this solution. Here's a Windows/File Explorer screenshot displaying a folder with four JPGs, which were the input files in a test run, and a single PDF, which was the resulting output file from the test run:

Create-Montage-PDF-from-JPGs.jpg
In that test run, all of the JPGs in the folder fit well on a single page in the output PDF file. But if there are too many images to fit on one page, the asker wants the resulting file to be a multi-page PDF. Also, the file name of each JPG should be shown below its thumbnail. All of this needs to be accomplished with a fully automated, unattended method, capable of being run by the Task Scheduler without user intervention.

One of the experts (Eirman) participating in that question recommended a terrific (and free!) utility (Snap2IMG) that can produce such contact sheets, but as a JPG file, not a PDF. Also, the utility presents a GUI, which (Eirman noted) could likely be automated with a scripting language like AutoHotkey, but it does not support command line
6
Rowby Goren Makes an Impact on Screen and Online
LVL 13
Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space.

w60 means Windows Vista or Windows Server 2008.
w61 means Windows 7 or Windows Server 2008 R2.

There are various guides found on the internet on how-to integrate updates into Windows installation media using dism.
This article is a post-integrate how-to to this numerous articles.
This article is addressed to users, who are comfortable using dism to mount, update, manage and unmount Windows Image files for deployment of Windows Systems.
So mounting and dismounting images is intentionally left out.

Problem:
Administrators often include windows update packages into their deployment images to save time when deploying.
In Windows 8 dism.exe has built-in command-line extensions to remove superseded updates from Windows 8 image files.
Earlier versions of Windows do not have this feature.
So when you integrate packages into a windows installation media (w60 or w61), superseded or outdated packages reside in the deployment image and use unneccessary space. This guide shows how to list and remove superseded packages from the command-line or by batch.

Short description for what you have to do before:
- Download Windows Updates for Windows (w60 or w61).
  Best practice is using wsus offline update.
- Mount Windows installation media.
- Apply packages to the mounted image.

The listings below offers two options.
The first option …
1
AutoHotkey logo
AutoHotkey is an excellent, free, open source programming/scripting language for Windows. It started out as a keyboard/mouse macros product, but has expanded into a robust language. This article provides an introduction to it, with links to additional resources for EE members who want to learn more.
27

Expert Comment

by:camtz
Excellent. Thanks Joe.
Carlos
0
LVL 67

Author Comment

by:Joe Winograd
You're welcome, Carlos, and thanks to you for the compliment. If you take a moment to click the thumbs-up icon at the bottom of the article, I''ll appreciate it — as you can see, you'll be endorsement #20. :) Regards, Joe
0
This article was inspired by a question here at Experts Exchange. The requirements stated in that question are (1) reduce the file size of a large number of JPG files in an extremely large number of subfolders; (2) perform that function without user intervention; (3) store the compressed files back into themselves, that is, after compression, each file overwrites itself.

The solution presented in this article meets those requirements. It is based on the excellent software package, GraphicsMagick (a fork of ImageMagick). GraphicsMagick is free (in every sense of the word), distributed under the MIT License.

The first step in the solution is to download and install GraphicsMagick from SourceForge (the latest release as of this article's publication is 1.3.21). The download folder looks like this:

GM-binaries.jpgSo the choices are:

GraphicsMagick-1.3.21-Q8-win32-dll.exe
GraphicsMagick-1.3.21-Q16-win32-dll.exe
GraphicsMagick-1.3.21-Q8-win64-dll.exe
GraphicsMagick-1.3.21-Q16-win64-dll.exe


As you can see in the file names above, there are two issues to consider with respect to the correct edition for you. The first is the so-called Quantum Depth. There are two possibilities — Quantum Depth of 8 (Q8) and Quantum Depth of 16 (Q16
7
LVL 28

Expert Comment

by:NVIT
Thanks for this article, Joe! I haven't taken a look yet but... Do you know if there is a switch to preserve the file date and time of modified files?
0
LVL 67

Author Comment

by:Joe Winograd
You're welcome, NVIT — glad you found it helpful. I'm pretty sure the off-the-shelf product can't do it, but there's a third-party patch that claims to provide a preserve-timestamp option for the mogrify command:
https://sourceforge.net/p/graphicsmagick/patches/45/

I haven't tried this and am curious about it, so if you give it a spin, please post your results.
Thanks, Joe
0
You may have already been in the need to update a whole folder stucture using a script. Robocopy does it well and even provides a list of non-updated files in a log (if asked to). Generally those files that were locked by a user or a process by the time the update script ran.

When only a few files are in use, you usually go to the "Manage open files" GUI on the server that provides the shared disk to force the files closed and re-run your script.

Now you may have a lot of those files or, even worse, you may want to schedule your script during the night, and you cannot because of those files that are blocked. Immediately, the OPENFILES /disconnect command comes to mind but this function does not allow you to close accessed files or folders in a recursive way. You close one file or one folder at a time OR you do it by username but then you have no more control on which folder you target.

I've looked for a decent workaround on the Internet and found none but complicated or manual procedures.
So I came up with my own piece of batch that fits in just a few couples …
0
If like me you are one who spends a lot of time working and scripting with cmd.exe, sometimes it is handy to be able to quickly view a calendar for a given month and year. This script will quickly do just that!  Save the code posted below to a .bat file called gcal.bat.  Then you will be able to view the current calendar (default) or specify a month and year, all with a simple command:

  gcal  [month]  [YYYY]

Examples:

  gcal  July
  gcal  August 2012
  gcal  09 2012
  gcal  10/2012
  gcal  nov .  dec .  jan 2013


Notes:  This is a pure script solution - no additional third party tools or scripts are required.  (EDIT: I now use the wmic program that comes with the OS to get the default month and year in a regionally non-dependant manner, but I left the "pure script" version in for reference, and for use with older OS versions.  See the formatParams section.)

The script is divided into four sections.  The first section (formatParams) validates and formats the input parameters (if any).  For flexibility the script will take various month formats.  The years is always a number from 1-9999.

The second section (getDayList) simply builds a string of numbers to represent the days in the specified month, 1 - 28, 29, 30, or 31 as required.

The third section (getSTARTDOW) actually does the work - determining which day of the week is the first of the month specified.

The fourth section (displayCalendar) displays the …
0

Expert Comment

by:Oleg Aney
Good script! I'll be using it in one of my powershell programmes.
1
When you receive another warning that your shared drive is almost full and you have asked your users to clean out old files again and again, here is a single command that may help.

This command will place all the files that have not been used recently into a folder but keep the directory structure in case you need to return any of them.

The first step is to check with the department that this can be done. Check they do not need to keep these files for historical or legal reasons. If they give you the go ahead then the next step is to make sure you have ‘robocopy’; you’ll find it in the Microsoft RKT
http://www.microsoft.com/download/en/details.aspx?DisplayLang=en&id=17657

Robocopy is a copy/move program like xcopy but with far more powerful command line switches.

What I would like is for it to go through
P:\Finance-Folder
and check each file for the last time it was used.  If it has not been used after a date I set then move it with its existing folders into a new folder.

To start with I am making the folder outside the folder I am working on. If you made it inside in its final destination then you would get into a loop where it would start to search inside itself and move its files into itself (not good).

So here is the command :

robocopy /s /MOVE /MINAGE:20100101 /r:1 /w:1 "P:\FINANCE-FOLDER" "P:\Archive"

Open in new window


/s = Hunt down through the folders.  You could use /e to also move empty ones and create a copy of the full structure.
/MOVE
1
LVL 15

Administrative Comment

by:Eric AKA Netminder
Congratulations!

Your article has been published.

ericpete
Page Editor
0
One of the most heavily touted new features of Windows Vista, Windows 2008 and Windows 7 has been the introduction of PowerShell, the new command line scripting environment Microsoft developed to help make life easier for Windows Administrators. But there's a problem. Windows Administrators around the Internet are looking at PowerShell with this deer-in-the-headlights look. They're afraid of it, because it's new, it's completely different from anything Windows has had before, and everyone around them is saying it's the best thing since...well...Active Directory.

I, like most Windows Administrators with little to no scripting experience, approached PowerShell with that icky-fingers feeling one gets when cleaning dead cockroaches off the floor. Scripting, for me, was always one of those things that just made me shiver and made my brain want to crawl out the back of my head and hide under a box in the corner.  

Then I got a new job and the first thing my new boss asked me to do was solve a number of problems that could only be done with PowerShell. So I had to learn and I had to do it fast. I looked around for some good resources and found plenty. The sad thing was that they all seemed to be written by and for people who had a lot more experience than I did. So I just decided to use my talent for figuring things out on my own and dove in.

Why PowerShell?

Before we get into the groove and start doing things with PowerShell, it's important to understand how it …
58
LVL 68

Expert Comment

by:Jim Horn
Excellent article.  Voted Yes.  Maybe I'll pass the 70-433 exam after all.
0
LVL 45

Expert Comment

by:footech
Even though I've been using PowerShell for a couple years now, sometimes I'll still read articles/blogs about things I'm already familiar with to get someone else's take on the matter.  This is a nice little intro to PS.

Suggested correction to:  "The other way to start powershell is to double-click a .ps1 file"
In my experience, the default association with .PS1 files is with Notepad, so double-clicking would just open the script in Notepad and not run it.

Another suggestion: "But what so many people who just give up on PowerShell realize is that..."
Change to:  "But what so many people who just give up on PowerShell don't realize is that..."
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 76

Author Comment

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

Expert Comment

by:Lofty Worm
very nice, going in my DOS batch links library!
0

Windows Batch

12K

Solutions

11K

Contributors

Batch files are text files containing a script of commands that are executed by the command interpreter on DOS, OS/2 and Windows systems. Most commonly, they are used to perform a series of functions that are repeated -- copying a set of files created daily with one step, for example.