Windows Batch





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

Hi Experts,

I want to create a Batch Job to be run from a Shortcut that will delete directories / files.  Since there is the chance the User accidently runs the Shortcut I want to give them the ability to abort the deleting.

In the attached Batch File I have a 'Choice' selection that is intended to branch to different Steps.  To test if it is branching correctly I have put a Pause in each branch.

However when I run the job it isn't pausing where it should.

Can you advise how to fix it.

Bob C.

I have a directory pathname stored in the variable

I am trying to get the "something" from this directory path and store it to another variable q.

Actually there are multiple servers with same path and I am trying to run a batch script in all of them to get the 6th subfolder (something) name which has Extract_Marker.txt.

The folder structure which leads to Extract_Marker.txt is same across all servers, only the "something" and "blah" varies.

Appreciate your help!


I had this question after viewing Finding the port number and storing it in a variable.
Using batch script in windows, I am trying to grep the port number (connector port value) from a file (abc.xml) which has the following data:

      Define a non-SSL HTTP/1.1 Connector on port 6080
    <Connector port="6080" protocol="HTTP/1.1"
               port="6080" protocol="HTTP/1.1"
    <!-- Define a SSL HTTP/1.1 Connector on port 6043
    <Connector port="6043" protocol="HTTP/1.1" SSLEnabled="true"

I'd like to store the value (6080) into a variable named port.

Please help me with a batch script. I tried using findstr /i to find the value but the I am unable to get the value.

Any help would be appreciated.

Hello :)

Here's what I'd like to do:

Say I have "c:\dirA" that has lots of files and subdirectories. I want to mirror that directory to "c:\dirB", adding new files/folders, deleting deleted files/folders, and updating changed files/folders. However, "c:\dirB" has two files in it "c:\dirB\File1.txt" and "c:\dirB\File2.txt" that I don't want deleted even though they are not in the source directory. Is there a way to do that with Robocopy? Any clever hacks you can think of to make this work?

I have a table that's already being populated by a SSIS package nightly. The table is never truncated. The table is below:
table 1
I want to add a new column for Credit Rating in the source code of the SSIS package. The joins are already there to support the data i want to add etc, so just adding the column would work.

My question is how would this impact the existing data in the table that don't have credit rating info.

Also when the job runs tonight, would it just automatically create the new column and add the info, not modifying the existing data?
Hope someone can help....
I need to create a  .bat file run from the desktop that; will open a command prompt, cd directory, and run an .exe file (already on the computer).  I would love for this to happen transparently to the end user if possible.  If you need the exact files and directories I can provide.
Hi Experts,

How can I set a folder full permission to "everyone" through command prompt?

I need to make this a part of a batch file.

Thank you
Can somebody help me to adjust the script that it will delete folders older the 30 days
This batch create  a directory in c:\backup  with the date and time(dutch), dump the sql backup, zip the file and delete the sql file

set ddump="c:\Program Files\MySQL\MySQL Server 5.7\bin"
set d7zip="C:\Program Files\7-Zip"
set ddate="%date:~-10,2%-%date:~-7,2%-%date:~-4,4%"
set ttime=%time:~0,2%.%time:~3,2%
set ddtback="c:\backup\%ddate%"" ""%ttime%"

md %ddtback%
%ddump%\mysqldump -u root -ppassword database > %ddtback%\database.sql"

%d7zip%\7z a -mx -tzip %ddtback%\ %ddtback%\*

del %ddtback%\database.sql
Help is much appreciated  Danny
I have a batch file that creates the same directories each time it runs.  There is no delete command in the syntax howver sometimes the folders are deleted.  Any idea why?

My syntax includes a series of commands to create folders.....

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (SET DATE=%%c-%%a-%%b)

rem File Information
SET FILE_DIR_ROOT="..\files"
SET IMPORT_SPEC_FILE_NAME="upload-spec.txt"
SET LOG_FILE_NAME="..\log\%DATE%.log"

rem Connection Information
SET USER="ghbv-z"
SET PASS="abcd"

I'm trying to get the first occurrence only of a record.

For example: I need to get the first time a store opens a account. I need the first time that customer account number will appear in the SQL table, not all subsequent times it will be there as they continue to do business against the customer number.

Please see the screenshot below. The highlighted parts would be my results. I tried using the min function to no avail. I may have use it wrong though.

First Occurence of a record
i need to take and query a list of computers using psexec or powershell to do the following.
1) find if version of adobe is greater than 9.40
2) if version is greater then silently uninstall program
3) install version 9.4 silently

$SoftwareKey = "HKLM:\Software" 
if ((Get-WmiObject Win32_OperatingSystem).OSArchitecture -match "64-bit") { $SoftwareKey = "HKLM:\Software\WOW6432Node" } 

if (Test-Path "$SoftwareKey\adobe\Acrobat Reader") { 
$adobeversion = get-childitem "$SoftwareKey\adobe\Acrobat Reader" 
foreach ($version in $adobeversion) { 
Write-Output "Found verstion $($version.PSChildName) of Adobe Reader" 

if ($version.PSCHILDNAME > 9.4) {
 #then uninstall the software
 # and install new software via uploaded exe

Open in new window

i think maybe generating a list first of who has it and and then maybe running a uninstall install against that list?  Help please?

here a batch script i came up with but obviously i can't get it to work.
@echo off
set CheckVersion=9.4.0
echo Checking Flash against version %CheckVersion% ...
for /f "tokens=3" %%a in ('reg query "HKEY_LOCAL_MACHINE\SOFTWARE\adobe\Acrobat Reader" /v Version 2^>NUL ^| find /i "Version"') do set DisplayVersion=%%a
echo Adobe Reader version: %DisplayVersion%; 
if "%DisplayVersion%"=="%CheckVersion%" (
  echo ... location has correct version ...
  goto :eof

echo Please wait while installing the new version ...
start "" /wait "c:\tempdir\adobeinstall.exe" /sAll
echo Done.

Open in new window

Hey Experts.  Working on a new script that will copy files from dir1 to dir2 but if the file being copied from dir1 to dir2 already exists in dir2, the file is moved to the Archive dir and then the copy job continues.

I can't seem to figure out the proper scripting for this.  Your help in accomplishing this would be appreciated.  Thanks Experts!

I found this but am having some trouble tweaking it to match what I wanted.  I grabbed it from and am still making changes.
@echo off

FOR /F "usebackq delims=;" %%I IN (`dir C:\Test\DIR1\*.* /s /b`) DO (
    IF NOT EXIST "C:\Test\DIR1\%%~nxI" (
        CALL :COPYFILE "%%I"
    ) ELSE (
        CALL :RENAME "%%I"


COPY "%1" "C:\Test\DIR2"

FOR /L %%N IN (1, 1, 1000) DO (
    IF NOT EXIST "j:\@PCBackup\PST\%~n1%%N%<wbr ></wbr>~x1" (
        COPY "%1" "j:\@PCBackup\PST\%~n1%%N%<wbr ></wbr>~x1"
        GOTO :EOF

Open in new window

I've got a surveillance system which stores all the video files in D:\Footage

I have to manually clear out the files every month to keep free space available as the surveillance program isn't smart enough to manage the disk space.

I don't care about footage more than 30 days old, so I want a script to delete anything older than 30 days in D:\Footage

Thanks in advance
I'm trying to create a batch file to prepare my systems for deploying a new AV solution.  To do that, I need to :

Allow file and printing sharing
Uninstall my current AV

I would like it to run silently and unattended so all my users need to do is double click on the bat file.  I need the bat to run as an administrator for the functions so, elevating privileges would be nice.

My basic bat looks like:

@Echo Off
wscript enable_fps.vbs
"%PROGRAMFILES%\Avira\AntiVir Desktop\setup.exe" /remsilent

The vbscript has the following but, I need to modify it to run unattended as well.  It would be nice to find a way to include this in the bat file so I don't have another separate file to worry about.

'* IntelliAdmin, LLC (2013)        *
'*     *
const HKEY_LOCAL_MACHINE = &H80000002

Sub enable_file_and_printer_sharing()
 set sFireWall = CreateObject("HNetCfg.FwMgr")
 sFireWall.LocalPolicy.CurrentProfile.Services.Item(NET_FW_SERVICE_FILE_AND_PRINT).Enabled = TRUE
End Sub

Sub disable_simple_file_sharing()
 Set sRegistry=GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")
 sRegistry.SetDWORDValue HKEY_LOCAL_MACHINE,"SYSTEM\CurrentControlSet\Control\Lsa","forceguest",0
end Sub

Sub disable_remote_uac()
 Set …
source directory contains the file i want to copy to another location.
source directory is c:\4
destination is c:\3

I need the batch file to copy the newest ".txt" file only (and place it in the destination.
I also need it to name the file "recent.txt" in the destination folder
Can someone write this for me?

As stated earlier.  a batch file is preferred but powershell may be required... i am unsure
Using:  MS-Word 2010 and Acrobat Pro 9

I have a few hundred Word docs in .docx format (all in same folder) which I need to convert to PDFs and to subsequently extend those PDFs so they are electronically signable by Acrobat Reader XI.  I can set this up so the parent folder starts on a Windows 7 Desktop with only .docx files which need to be converted and extended.

The manual process I'm using works but is obviously very time consuming when dealing with hundreds of files.  The steps are:

1.  Open .docx in Word 2010
2.  Ensure 'Display for Review' is set to 'Final' (some docs open up with 'Final:  Show Markup' which cause the markups to be converted to PDF is their display isn't set correctly); this is done through tab:  'Review > Show Final'
3.  Save .docx (this simply ensures that subsequent web views of the doc show up with Display for Review set to 'Final')
4.  Save as .pdf (File > Save As > Save as Type:  PDF (*.pdf)  )
5.  Open .pdf in Acrobat Pro 9
6.  Extend Features in Adobe Reader and save back on top of same filename (Advanced > Extend Features in Adobe Reader ... > Save Now > Save > Yes )

How can I automate this process so that all .docx in a given source folder end up being converted to extended pdfs in the same source folder (viz.:  FolderA starts with filename1.docx, filename2.docx ... FolderA finishes with filename1.docx, filename1.pdf, filename2.docx, filename2.pdf)

Hi Experts!  I am putting a script together that will check c:\dir to see if file.txt exists.  If it exists, I'd like to rename the file to .old

How do I write this?  I needed the experts to help with this.

Here is what I have.  It's a work in progress.

if exist  c:\dir\file.txt (
    ren file.old
) else (
    goto :eof

Open in new window

Does anyone have a batch or powershell script to ping an ip for a time period (i.e. 8 hours) and output to a file.

I'm trying to ping heart beat IP's throughout the day to troubleshoot possible network issues.  

Is there a switch for the ping -t command that will run for say 8 hours then stop?
Hi Experts.  I'm using the following command to output a list of processes running on a computer.  I wanted to remove some of the columns that are being written to the log file but wasn't sure if it could be done.

pslist | findstr.exe /v /i /r /c:"^chrome\>" /c:"^sVchost\>" >> %log%

Open in new window

I appreciate your help with this!
Hey Experts.  I have a small batch file that outputs the results of pslist (processes running on computer) into a log file.  The output is great but I'm wanting to exclude certain things from ending up in the log file.  How do I control what is echo'd or parse the results in the log file?  Here is a small sample of what is in the log file:

Wed 03/09/2016 10:39:45.97
Process information for PC1:

Name                Pid Pri Thd  Hnd   Priv        CPU Time    Elapsed Time
Idle                  0   0   4    0      0  1194:25:03.642   325:47:59.227
System                4   8 156  684    608     0:49:39.182   325:47:59.227
smss                332  11   2   32    544     0:00:00.156   325:47:59.102
csrss               548  13   9  977   3032     0:00:22.074   325:47:53.096
wininit             620  13   3   81   2244     0:00:00.109   325:47:49.570
csrss               644  13  18  959  24484     0:31:05.631   325:47:49.555
services            688   9   6  359  10420     0:00:59.670   325:47:49.445
lsass               712   9  10 1268  10848     0:03:33.705   325:47:49.367
lsm                 720   8   9  198   3268     0:00:04.664   325:47:49.367
winlogon            824  13   3  134   3772     0:00:00.577   325:47:48.681
svchost             888   8  12  421   6448     0:01:22.290   325:47:45.031
nvvsvc              952   8   5  116   3264     0:00:00.140   325:47:44.968
nvwmi64             976   8   3   63   2064     0:00:00.062   325:47:44.719
Basically I'm trying to update around 250 pc's with the .net 3.5 framework.  I know that in windows 8.1 this is broken so the the only way to use the following.

DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:\\servername\sources\sxs

Easy, but I want to automate this task so that it doesn't need an elevated command prompt to run it.  I tried to create a scheduled task using the run as administrator but it still doesn't work, it errors with 0x80070005 when I check the gpresult /h.

Is it possible to run the dism command as an elevated user or some other method to get this to work. I thought powershell may work but that also needs elevated privileges.

At this rate I will have to install manually on every PC!!
Hello experts,

I have the following script which I use to align and copy from a root folder to a dest folder

@echo off
setlocal EnableDelayedExpansion

REM Define possible backup drives, and the root for backup folders
set ConfigFile=config.txt

REM define robocopy options
set Options=/XJ /E /R:1 /W:1 /NP

REM Default options
set FullPath=1
set DateStamp=1

REM If config file exists load settings from it
if exist "%ConfigFile%" (
  for /f "usebackq tokens=*" %%A in ("%ConfigFile%") do (
    set %%~A

REM Build a date stamp for backup folder in YYYYMMDD, unless config says not to
if %DateStamp% EQU 1 (
  set Stamp=%DATE:~-4%%DATE:~-10,2%%DATE:~-7,2%__%TIME:~0,2%-%TIME:~3,2%-%TIME:~6,2%
  set Stamp=!Stamp: =0!\
) else (
  set Stamp=

REM Define possible backup drives, and the root for backup folders
set LogFile=%DestDir%\CopyLog(%Stamp%).txt

REM Create the directory for todays backups
if not exist "%DestDir%\%Stamp%\" md "%DestDir%\%Stamp%\"

REM Do the backups, dest path basedon config option
for %%A in (%FromDirs%) do (
  if %FullPath% EQU 1 (
    robocopy "%%~A" "%DestDir%\%Stamp%%%~pnxA" %Options%  /LOG+:"%LogFile%"
  ) else (
    robocopy "%%~A" "%DestDir%\%Stamp%%%~nxA" %Options%  /LOG+:"%LogFile%"

echo Copy process has been done

Open in new window

The Question is reported at:

To launch the script a config.txt needs to exist

I would like to use this excellent script…
Can somebody help me to change the underneath CMD script from oBdA to find 3 programs and run 2nd  command when the first is finished and the 3rd when the 2nd is finished (a 10 second delay between commands is also good)

Thanks Danny
@echo off
setlocal enabledelayedexpansion
if "%~1"=="" (
      set /p FileName=Give the filename:
      if "!FileName!"=="" goto :eof
) else (
      set FileName=%~1
call :Where Folder "%FileName%"
if "%Folder%"=="" (
      echo %FileName% not found.
      exit /b 1
echo Folder: %Folder%

REM ========== Only function after this line! ==========
goto :eof
:Where &lt;Variable&gt; &lt;File&gt;
set %~1=%~dp$PATH:2
if not "!%~1!"=="" goto :eof
echo '%~2' not found in path; searching C: ...
for /f "delims=" %%a in ('dir /a:-d /s /b "C:\%~2"') do (set %~1=%%~dpa&goto :eof)
set %~1=
goto :eof
McAfee provided this ripper tool because we are running into many problems with uninstalling McAfee VSE locally on Windows 2003 servers. I need to deploy this ripper tool to 400 remote machines (all the same with same OS version, Server 2003), and have it execute on the remote machines. Is there a script like psexec I can run to accomplish this? If so, can someone detail the steps? I have domain admin rights, and I am thinking I need to enter my credentials somewhere within the script perhaps.

Let me detail what I hope to accomplish. We can use the below example to write the script or bat file.

1. From the ePO server (server name is "ePO1"), I placed the ripper tool in the following path: "C:\VSEripper" folder. The ripper tool is named "rip.exe".
2. I want to execuite the ripper tool from the "ePO1" server. Need the ripper tool to execute on a few remote servers. E.g. - server1, server2, and server3. How would I write a script to accomplish this?
I have thousand of PDF files in a folder, I know of a few hundred I need, I need a script where I can tell the script what .pdf files I need form the folder and it will dump them to a separate folder.

Windows Batch





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.