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

Hello All,

I’m having problems installing a Local printer port via script. For years I’ve used scripts like below.
Creates Port:
cscript %windir%\system32\printing_admin_scripts\en-us\prnport.vbs -a -r "IP_1.1.1.1" -h "" -o raw

Open in new window

Installs Printer to above specified port:
rundll32.exe printui.dll,PrintUIEntry /if /b "Printer Name" /f “Printer Driver Path\file.inf" /r "IP_1.1.1.1" /m "Printer XXX"

Open in new window

I’ve used this successfully for decades, it keeps everything exactly the same and saves tons of time.

My problem:
I need to make a nul printer, which I can do manually no problem, but I’ll be damned if I can figure out how to make a local nul port with a script.
This works fine if I manually make the Nul Printer through the gui:
rundll32.exe printui.dll,PrintUIEntry /if /b "NullPrinter" /f "%windir%\inf\ntprint.inf" /r "nul:" /m "Printer XXX"

Open in new window

but I would rather not have to create the NUL: port manually on 300 systems if possible.

The problem I’m sure is the” –h” switch,  which tells it there is an IP address. If I run it like:
cscript %windir%\system32\printing_admin_scripts\en-us\prnport.vbs -a -r "nul:" -h "nul:" -o raw

Open in new window

It does create the port, but it creates it as a Standard TCP/IP port which of course is not what I need and does not function as a NUL port. I’ve tried every variation of syntax I can come up with and none seem to work. I’ve looked for the last couple of hours on the internet and everything always references creating an IP port not a Local Port like NUL.

Any help would be great.
OWASP: Forgery and Phishing
LVL 19
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Hello experts,

I am looking for a procedure that covers the following requirement:
Þ      Loop the various files located in a directory (drill down not needed)
Þ      Get the number of lines of each file
Þ      Output file name of each file located in the directory;Count Lines in a csv file.
Þ      Csv file should be composed as following Count-files_YYYYMMDD_HHMMSS.csv
Þ      Directory will be composed exclusively of txt, csv, xls, xlsx files. If get count of xls, xlsx is complicated, I will manage just txt and csv files
Þ      Powershell, Windows Batch, VB Script are more than welcome.

If you have questions, please contact me.
Send Message Command to remote computer.

I would like to run the Send Message command from one windows computer to another windows computer, and have the message shows up on another computer screen  even if it is locked

Thank you
Simple process how do you call a macro from a script


Macro called 'Extract'
Hello experts,

The following procedure allows me to archive files based on a variable on a monthly folder.
It comes from the following question:
@echo off
setlocal EnableDelayedExpansion
set CurrentDir=%~dp0
REM Define base for folders, files, and days to keep files before moving
set InputFolder="%CurrentDir%\Files1","%CurrentDir%\Files2","%CurrentDir%\Files3"
set ArchiveFolder=%CurrentDir%Archive
set LogFile="%CurrentDir%\log.txt"
set KeepDays=2

REM Delete any old log file
if exist "%LogFile%" del "%LogFile%"

rem Calculate date to keep files older than
call :CalcKeepDate

REM Loop over each input folder to work
for %%F in (%InputFolder%) do (
    if exist "%%~F\" (
        call :ProcessFolder "%%~F\"
    ) else (
        echo *WARNING* Input folder "%%~F" does not exist.

REM Done
exit /b

    rem Build vbscript helper to calculate file date minus keep days
    set TempVbs=%temp%\%~n0.vbs
    echo >"%TempVbs%" d=DateAdd("d",-%KeepDays%,Now)
    echo >>"%TempVbs%" WScript.Echo Year(d) ^& Right(100+Month(d),2) ^& Right(100+Day(d),2)

    rem Execute vbscript and get file date - keep days (in YYYYMMDD format)
    for /F "tokens=*" %%A in ('cscript //nologo "%TempVbs%"') do set 

Open in new window

I'm trying to run a batch file (from SCCM) to delete a registry key on any 64-bit Windows 7/10 computer.  I thought I had it working, but now it's not behaving consistently.  

I "thought" the following worked :

%windir%\sysnative\reg.exe DELETE HKCU\SOFTWARE\<key to delete> /f

But it's not working now.  

I need this to work as a deployed SCCM application as well as manually.

Any help is greatly appreciated!!
Hello experts,

The following procedure allows me to transfer specific files from temp to requests folder and launch API java.

echo off
setlocal EnableDelayedExpansion

set APP_NAME=api-name
rem set APP_VERSION=1.0.1
set MODE=2

rem Setting folders path

set BIN_DIR= %APP_PATH%\bin
set LIB_DIR=%APP_PATH%\lib
set CONF_DIR=%APP_PATH%\conf
set VAR_DIR=%APP_PATH%\var
set LOG_DIR=%APP_PATH%\log
set FLG_DIR=%APP_PATH%\flag
cd %BIN_DIR%
set BaseDir=%APP_PATH_FOLDERS%\CostCodes2\Temp
set DestDir=%APP_PATH_FOLDERS%\CostCodes2\Requests
set MaxFiles=18

call :GetStamp

set StampInitial=%Stamp%
set LogFile=%LOG_DIR%\C1_%StampInitial%_MOVE.log

echo %Stamp%: Base folder is "%BaseDir%">>"%LogFile%"
call :GetStamp
echo %Stamp%: Destination folder is "%DestDir%">>"%LogFile%"

set i=0
for /f "tokens=*" %%A in ('dir /b /o-d /a-d "%BaseDir%\*.csv"') do (
	if !i! GEQ %MaxFiles% goto :Movedone
    move "%BaseDir%\%%~A" "%DestDir%">NUL
    call :GetStamp
    echo !Stamp!: Moved file "%%~A">>"%LogFile%"
	set /a i+=1

call :GetStamp
echo %Stamp%: Total files moved = %i% >>"%LogFile%"


rem --------------------------------------
rem Call API java
rem --------------------------------------

set JAVA_ARGS=-showversion -Dlog4j.overwrite=true -Xmx4096m -Duse_description=true
java %JAVA_ARGS% -jar "..\lib\mstt-synchro-cost-codes-2.jar" 

Open in new window

I'm needing to create a batch file that will format a USB drive which is on a different computer.  Below is what I have but isn't working.  The USB drive is on a computer called it-metrics and I do have full admin access and this drive is shared with me.  The drive letter is 'D'.  

@echo off
for &#37;%i in (\\it-metrics\D) do format %%i /FS:NTFS /x /q
Good day all,

im trying to make a Batch file that Copies Dell Switch Config to the Switch.
The Config is in .txt Format so im trying to setup a Batch File that Copies the Config and login to the Switch Via Kitty/Putty and past the config.

Thank you in Advance.
Hello experts,

I have the following pgsql command which allows me to export tables through to csv:

\copy (SELECT * FROM "schema"."tablename") to 'C:\Users\Downloads\tablename.csv' DELIMITER ';' CSV HEADER;

I was wondering how to set up a powershell & windows batch or vbscript with the following information:

1-New Server registration
20191025_154349-screenshot.png2-Declare as variable:
Table to export
Directory in which will be export csv file.

Thank you for your help.
Bootstrap 4: Exploring New Features
LVL 19
Bootstrap 4: Exploring New Features

Learn how to use and navigate the new features included in Bootstrap 4, the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.

What script/powershell command would be used to delete any file in a directory that starts with anything but a number (0-9) or the extension is .tmp. We have a system that only uses numbers and users copy files to the directory accidentally that need to be deleted automatically.
Hello experts,

I am looking for a script that cover the following requirement:
Remove all files located in a folder which start with specific string.
The idea is to declare specific string multiple times in a variable.
StringToRemove = “KO”; ‘OLD”; "ERR"
All the files which contain those string reported in StringToRemove should be removed.
Drill down mode required. In order to also remove all files located in subfolders.

Windows Batch & PowerShell & Vb Script are more than welcome.

If you have question, please contact me.

Thank you for your help.
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

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

Microsoft Azure 2017
LVL 19
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

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.
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

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.