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,

Not sure For /F is correct solution but I think it is.

Desired Result for the 'Result.bat' file:
My current For /F which is not working.  Never even makes it to the pause for some reason.

@echo off

set AppName=Fin

FOR /f "tokens=1 delims," %%G IN ("D:\Years.csv" DO @echo "call epmautomate exportData %AppName%_DATA_%%G" > "D:\Result.txt"


exit /b

Open in new window

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.

Can anyone recommend a good batch file to EXE compiler?
Experts, I have a printer mapping script that installs printers based on the user's group membership (due to the 50+ printers we have in this office, I can't use group policies).

@echo off

setlocal enabledelayedexpansion

echo Connecting Printers...
set PriorityDefaultPrinterSet=0
for /f "tokens=1-3 delims=-." %%a in ('n:\ifmember.exe /list ^| find /i "group %UserDomain%\Prt-" ^| sort') do (
  echo Connecting %%b %%c
  rundll32 printui.dll,PrintUIEntry /in /q /n\\w2k8ps01\%%b
  if not "!PriorityDefaultPrinterSet!" == "0" goto not_def
	echo ...Setting as default printer
	rundll32 printui.dll,PrintUIEntry /y /n\\w2k8ps01\%%b
  if /i "%%c"=="D" set PriorityDefaultPrinterSet=1


Open in new window

As we migrate the users from Windows 7 to Windows 10, I need to change this script to include the new print server (w2k16ps01).  I tried just changing the server name in the script but the printers aren't installing in our testing.

Can someone look at this script and verify if it will run on Windows 10 or if there is different verbiage that I need to include?

Thanks Experts.
Hello experts,

I am looking for a procedure to copy the various .log files which contains at least one line that start with : 1; and finish with ;17 :

AsOfDate variable required in order to exclude files older than this date (Creation or Modified date).

Windows batch or Powershell approach are more than welcome
If you have questions, please contact me
Hello experts,

I have the following .bat.

"C:\API\file.bat" NO_THRESHOLD

Open in new window

I would like to add a previous line to force the run as administrator.

How should I proceed?

Thank you for your help.
Hello experts,

The following procedure allows me to loop on log files based on their contain, copy them and their csv equivalent into specific folders.

I would like to add the following requirement:
-Instead of looping all .log files located in specific directory I would like to define an AsOfDate variable to retain just files which are equal or newer of this AsOfDate based on Creation Date located in specific directory.
Example: If I report 20190810 All the files older (excluded than this day should be skipped)

If you have questions, please let me know:

Rem =============================================================
Rem Move log files ant it csv equivalent if files contain at least 
Rem one line which doesn't start with 0
Rem =============================================================
Rem @echo off
setlocal EnableDelayedExpansion

rem Define paths and files to work with
set BaseDir=C:\Base\log
set DestLog=%cd%\DestLog
set DestCsv=%cd%\DestCsv
set ErrorLog=%cd%\Log-Error.txt
set ErrorCsv=%cd%\Csv-Error.txt

rem Define loop timing settings
set LoopDelaySeconds=10
set LoopDurationHours=60

rem Determine end time for looping
Call :CalcEndTime

    rem Loop until end time reached
    Call :GetCurrentTime
    if %CurrentTime% GTR %EndTime% goto :Done

    rem Copy selected files and log results
    for /f "tokens=*" %%A in ('findstr /m /b /v /c:"0;" "%BaseDir%\*.log"') do (
            echo copying "%BaseDir%\%%~nxA" to "%DestLog%"

Open in new window

I have a powershell script that runs in two parts the first part reboots a windows server 2008 R2 box this part works great, the second part of the script logs in a domain user account with autologon.exe then runs an executable with various parameters then sends an email with the process id and true/false state of of the process id. The script works fine wrapped around a windows task scheduler entry. The issue is it runs in the background and does not display the exe window on the desktop. We have to be able to  interface with the program.  How do i make this script run interactively on the desktop? Below is the powershell script.

# Bert 7-14-18 Autologon to OSP server and run OSP web server GUI and web services

# =============================================================================================
# Autologon to Sage user account
start-process c:\script\autologon.exe -ArgumentList "test","","test2019","/accepteula"
# =============================================================================================

# =============================================================================================
# Set path location
set-location "c:\sage\sage 100 2018 web engine\webeng\home\"
# Start ProvideX web config GUI
.\pvxwin32.exe c:\sage\sage 100 2018 web engine\webeng\home\webcfg.ini *web/webcfg
# Start base launcher
.\pvxwin32.exe webhide.ini *web\webserv
# Start MAS90 web server instance
.\pvxwin32.exe webhide.ini *web/websport -ARG "MAS90"

Open in new window

Quick question, how do I extract the FULL OU path  using SET /F. Have everything else working but can extract the OU in the popup and generated text file.

Any help appreciated with the BOLD bit of the code.



@echo off & setlocal
Color 0A
Title Get Report on %computername%
if %os%==Windows_NT goto WINNT
goto NOCON

echo .Using a Windows NT based system
REM set variables
set system=
set manufacturer=
set model=
set serialnumber=
set osname=
set sp=
set totalMem=
set availableMem=
set usedMem=
Set IP=
Set OU=

echo Getting data [Computer: %computername%]
echo Please Wait....

REM Get Computer Name
FOR /F "tokens=2 delims='='" %%A in ('wmic OS Get csname /value') do SET system=%%A

REM Get Computer Manufacturer
FOR /F "tokens=2 delims='='" %%A in ('wmic ComputerSystem Get Manufacturer /value') do SET manufacturer=%%A

REM Get Computer Model
FOR /F "tokens=2 delims='='" %%A in ('wmic ComputerSystem Get Model /value') do SET model=%%A

REM Get Computer Serial Number
FOR /F "tokens=2 delims='='" %%A in ('wmic Bios Get SerialNumber /value') do SET serialnumber=%%A

REM Get Computer OS
FOR /F "tokens=2 delims='='" %%A in ('wmic os get Name /value') do SET osname=%%A
FOR /F "tokens=1 delims='|'" %%A in ("%osname%") do SET osname=%%A

REM Get Computer OS SP
FOR /F "tokens=2 delims='='" %%A in ('wmic os get ServicePackMajorVersion /value') do SET sp=%%A

[b]REM Get Organisational Unit
for /f "delims=* 

Open in new window


How can I run a .jar file at computer startup, and have the application running all the time, until computer shutdown?

Hello experts,

I have multiple files located in C:\RootFolder.
I am looking for a procedure to rename the various files with an specific Prefix and add Modified Date at the end.
NewName of toto.jpg=>Picuture_20190926_043017

  • The various files should contains:
  • Picture_20190926_042516 (Modified date)
  • If a file contains the same modified date add a +1
  • Example Picture_20190926_042613 Picture-1_20190926_042613
  • Drill down not necessary.

Windows batch & Powershell approach are more than welcome.

If you have questions please contact me.
CompTIA Security+
LVL 13
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Hello experts,

I am trying to document how to avoid running for real and just list the following command (prior to run for real).
  • Robocopy "C:\Source" "C:\Destination" /L rem: Just List files and folder
  • Del: del /q /s /f "C:\FolderName"
  • Rmdir: rmdir "foldername" /q /s
  • Move:move *.filetype %userprofile%\folder
  • Forfiles: ForFiles /p "C:\FolderName" /s /d -30 /c "cmd /c if @isdir == FALSE if /i @ext == \"txt\" del @file"
  • Remove-Item: Remove-Item C:\FolderName\* -recurse -verbose

If you have questions, please contact me.
Thank you for your help.
Hello experts,

I have:
-SourceFolder and DestinationFolder
I would like to copy files located in SourceFolder which don't exist in DestinationFolder.
What is the most straightforward approach to do this?
Windows batch through robocopy & Powershell or VBS ?

Thank you for your help.
looking for replacement the old 32 bit TOUCH program to change by commandline the date for file   like it was in dos
its not running in 64 bit

touch j:\*,*   or touch j:\*.txt    will files selected to today date
Is there any way to shorten file names in a folder using a program or batch file.  We have these dumb long file names that need to be fixed because we can't zip files due to long filenames.

Hello experts,

I have the following ahk file attached.
I am looking for a procedure that covers the following needs:
-Read ahk file
-Generate an Output-(file-name-of-ahk-file)_yyyymmdd_hhmmss.csv file with headers: Item; Hotkeys and the following
     -Based on information read of ahk file, report the second text line after the following line: ";===================================
      Instructions & Variables information should not be reported in the csv file
     -Based on information read of ahk file, report the right after line which finish & or contains with ::
I attached dummy-file and output-file as I expect that the procedure generate csv file.

Windows Batch & Powershell & VB Script approaches are more than welcome.
If you have questions, please contact me.

Thank you for your help.
I am writing a cmd file to utilize robocopy as an automated backup. I want to create a new log every time it runs that is date stamped as part of the log name. I am using the script below. The log was named Tue09172019-8212265Home. However I want the format to be yyyymmdd-hhmm so in this case 20190917-0821Home.

set tdate=%date: =%
set tdate=%tdate:/=%
set ttime=%time::=%
set ttime=%ttime:.=%
set ttime=%ttime: =%

Robocopy G:\Home F:\Home /e /b /xo /copyall /dcopy:DAT /mt /LOG:F:Logs\%tdate%-%ttime%Home.log /NFL /NDL
Can someone please help us with a bat script that will wait 5 minutes and then return a 0 on success?

We need to call the script from this registry key : HKLM\Software\Citrix\MachineIdentityServiceAgent\ImagePreparation\After

The values are expected to be an executable or script (bat), returning 0 on success

Basically we need to VM to wait 5 minutes before it's shutdown by the system on returning a 0 on success the shutdown will triggered.  

Thank you!
Hello experts,
I am looking for a script to replace single space or multiple spaces at files and folders located in a root folder by "-" characters
The idea is to have as variables:
      The character that is going to replace single or multiple spaces
      Drill down mode flag
Powershell & VB Script & Windows Batch approaches are more than welcome.
Thank you for your help.
I'm trying to create a batch file that will add the current date to a file. I found this online - but it only works when you enter it directly on the command line
for /f "tokens=1-5 delims=/ " %d in ("%date%") do rename "filename.pdf" filename_%g%e%f.pdf

If its in a bat file I receive this message
dategf.pdf was unexpected at this time.
screen shot of running commands
I'm looking for a solution and I'm not tied to this one if you have a better option.

Thank you!
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.

Hello experts,
I am looking for a script that covers the following requirement:
Find duplicate files in a folder:
Keep newest file remove oldest file.
Powershell & Windows batch approaches are more than welcome.
Thank you f or your help.
I wud like to prevent non-admin users from amending the following
2 registry values:

Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings
a) ProxyEnable
b) ProxyServer

Seen the following link but still can't grasp it, so will need the
exact setacl command to be applied on the registry:

Another EE expert has given me the PS method below
but we don't have access to PS & would like to do it in
batch scripts/commands.

1:$acl = Get-Acl "HKLM:\SOFTWARE\Example"
2:$person = [System.Security.Principal.NTAccount]"BuiltIn\Users"          
3:$access = [System.Security.AccessControl.RegistryRights]"FullControl"
4:$inheritance = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit,ObjectInherit"
5:$propagation = [System.Security.AccessControl.PropagationFlags]"None"
6:$type = [System.Security.AccessControl.AccessControlType]"Allow"
7:$rule = New-Object System.Security.AccessControl.RegistryAccessRule($person,$access,$inheritance,$propagation,$type)
9:$acl |Set-Acl
I have 2 registry values that I use regedit to update & delete respectively.
What's the command (in Command prompt) to make the same change?

Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings

a) ProxyEnable : would like to change it's value from 1 to 0
b) ProxyServer : to remove any values in it (ie make it nul value)
I am trying to create a Robocopy script that will copy files from one location to another location and purge the source files based on the timestamp. The script runs every hour at :00 and it copies the files to another location but, I want it to only delete the source files that are older than 15 minutes prior to the top of the hour. For example, the script runs at 11pm and I want it to only delete files older than 10:45pm. This is what I have currently in my script but, I don't know what switch(es) to use to do the file delete based on timestamp.

robocopy "\\\Share\CX" "D:\FC_Import\CXM" /S /E /SEC /MOV /COPYALL /V /NP /LOG+:"d:\Robocopy.txt" /R:3 /W:5
Someone from another organization told me he has an
in-house developed script that could read incoming emails
(in particular those originating from outside the organization)
for URLs/links, originating IP & attachments: the script will
extract the links, IP & attachments, check them in virustotal
& hold back the email if it's a known IOC by any of the
security products in VT.

I have a tool from VT (vt.exe) that could post IP, hashes
& links to VT but I don't know how to extract the links,
attachments & originating IP of emails.

The acquaintance cant share the script as their intellectual
property: they used in on their on-prem Exchange.

Anyone can share any free tools, batch or VB scripts ?
Ideally not a PS script but if it has to be a PS script, then
I'll take it as well.

We are using MS Exchange Online.

One more feature to add in:
will be nice if the script could check if the originating
IP belongs to the sender's domain (which is visible
to the email recipient) & if not hold back the email
as well & notify our IT support by email

I'm looking for help writing a batch file.

I want to use it as part of a start up GPO,

Install an MSI silently, if the folder already exists skip the install, report the results to a temp.log.

Can someone please assist - thanks

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.