Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


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

I have a startup script that needs to grab values from another script. (cmd files)

The variable values do not populate without delayedexpansion ( I am ok with this except for one thing)

I have a value that contains a "!" which gets lost once read with delayed expansion on - I am unable to manually adjust this value since it is dynamic.

Any ideas on how to work around this ?


net use !server!\filepath /user:!user! '!password!'

The password sometimes contains an exclamation and causes a break is there any way to handle this ?
Free Tool: Subnet Calculator
LVL 10
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

When I use PsExec with a batch file residing on a remote computer that asks for the %USERPROFILE% or %USERNAME% of the remote session it always returns my username or user profile path.

How do I run this same command so that it returns the currently logged in user's %USERPROFILE% or %USERNAME% without modifying the commands in the bat file or having the user profile credentials from the currently logged in remote user.

These are on Windows 7 64-bit machines that reside within a domain.
I have a batch file I need to run in windows scheduler.


It appears that I am having issues mastering windows schedular to execute this file:

I have tried several things in the action tab:

putting in \\sharedrive\operations\daily in the Start-in block, and master.bat in the Program block. results in cannot access directory error
Putting in \\sharedrive\operations\daily\master.bat into the Program block, and got a successful error.
How do I set this up correctly so I can call UNC-bast batch files as if they were local? I realize that mapped-drives are a problem, so here I am.

Hi all,
I put together a batch file that will ping a host(s) from a file and if the host is online it will run a few WMIC commands and export the results.  I'm getting the desired results BUT also getting an additional line of data from the loop.  Any advice is appreciated!!

@echo off
setlocal EnableDelayedExpansion
rem Define output file location
set OutputFile=WMIHost2IP_Info.csv
set IpList=wmihostname.txt

rem Overwrite output file and add header line
echo "IP","SystemName","User","OS","TaniumState" > "%OutputFile%"

rem Gather all data desired
for /f "usebackq tokens=1" %%l in ("%IpList%") do (

      rem ping the ip to see if it is online or offline
       ping.exe -n 1  -w 100 %%l >nul && set ok=Online|| set ok=Offline

rem If online.....get WMIC infoto the outputfile
      If !ok! =="Online" do (
      echo %%l  is !ok!
       for /f "skip=2 tokens=2 delims=," %%a in ('wmic /node:"%%l" ComputerSystem GET Name /format:csv') do (
              for /f "skip=2 tokens=2 delims=," %%b in ('wmic /node:"%%l" ComputerSystem GET UserName /format:csv') do (
                    for /f "skip=2 tokens=2 delims=," %%c in ('wmic /node:"%%l" OS get Name /format:csv') do (
                          for /f "skip=2 tokens=2 delims=," %%d in ('wmic /node:"%%l" service WHERE "Name = 'Tanium Client'" GET State /format:csv') do (
                  rem Write merged results to output file
                  ::echo %%~l is !ok!
                  echo "%%~l","%%~a","%%~b","%%~c","%%~d">>"%OutputFile%"

I'm working with Windows Scheduler and windows batch files.

Here's what I have:

in \\SHARE\PROCESSOR\  I have three objects:
processA (FOLDER)

inside each folder I have a python executable, plus other artifacts the python code needs to operate.

I have two users:  myself and the service account.  Both AD users.

The problem is not the batch.  When I click on MASTER.bat in folder \\SHARE\PROCESSOR\ it all works.
If I use runas on the command line to start MASTER.bat, still no problem.  everything good.

My issue is with windows scheduler.

Scheduled task
The action settings are:
Program/script:  \\SHARE\folder\MASTEr.bat
Arguments and Start in are both blank.

When this is executed by Windows Scheduler.  It runs for one minute then exits successfully with error code: 2147942401

This is where I take issue because I can see the batch file plus associated python scripts in the task scheduler.  

What I need:
I need the scheduler to not lose focus on the task.  If the action takes too long, i need it to be able to stop Master.bat.

Any wisdom would be greatly appreciated.

Since installing Office 2013 in our environment, we have to manually turn off a Windows system setting, 'Animate controls and elements inside windows' due to performance issues.

System >> Advanced System Settings >> Advanced >> Performance, Settings >> under Custom, 'Animate controls and elements inside windows' check box.

Has anyone done this via batch / GPO / or any other mass method successfully?

This is for Win 7 SP1 Enterprise.
Hi Experts,

Good Day,,,

According to my work, I need to ftp files from one server to another using batchscript.I am able to do the same.
logs are getting saved into outputlog.txt file which is present in the same server path.

My requirement is ,need to send a mail with attaching outputlog.txt .
If it is successful (means errorlevel=0 ) then subject should be ftp successfully completed.And if it get failed,then subject should be ftp failed.In both the cases, log file should get attached.

Any help regarding this would be highly appreciated.
Thanks in Advance..
Hi Experts
i have an application no working with all features except i run it as administrator however the user is a domain user
i need batch file to run this app as administrator without give the domain user admin password
Run a batch file during Shutdown process -

I currently have a batch file that deletes files.  However, I need to be able to call this batch file when the shutdown process starts - is this possible in XP.  I have been unable to find anything.
Hello Experts,

We have a multiple folders in d drive these all folders have sub folder which name is LogFiles, we need to forcefully delete all LogFiles folders only from a batch file.


Please suggest
Enroll in September's Course of the Month
LVL 10
Enroll in September's Course of the Month

This month’s featured course covers 16 hours of training in installation, management, and deployment of VMware vSphere virtualization environments. It's free for Premium Members, Team Accounts, and Qualified Experts!

how to align these lines vertically?

andreas savini marcos
streptcoc salim sarim
blah sa ma ca ba ha.

Open in new window


Open in new window

I will have several files during the day. Cannot select the latest with timestamp, i need to have to file with the greatest id.

The file name is in a format: [standardname]_[date]_[id].csv. Eg invoices_2017_09_19_186.csv
I am trying to deploy Intune to all the computers in my company.  Unfortunately, MS requires the user to be a local admin to join Intune.  These are all AD Domain Joined.  I am looking for a way to give the logged in user local admin rights, have them connect to Intune with their username and password and then remove them from the local admin group.  So far I have this for my script:

Net localgroup administrators “domain\%username%” /add
Start ms-device-enrollment:?mode=mdm
Timeout 300
Net localgroup administrators “domain\%username%” /delete

It works fine if a domain admin right clicks and runs the batch file as administrator.  I would like it run as a logon script one time.  I also tried to copy the file to common startup folder so it would run at logon, but get access denied on the first line.  The rest of the script runs without error.  Has anyone had success joining computers to Intune without manually making users local admins?
There are a few PC's on my network that have unknown versions of CCLEANER on them.  CCLEANER doesn't update automatically so they would have whatever version that was current at the time.  Since CCLEANER now is being bundled with MALWARE, I need to just remove it from my network.  Looking for a script that I can add to my login scripts, or even a command line that I can run remotely to remove any and all versions on a PC, or preferably  the entire network.  

Thanks in advance.
I need help. How to create batch file to import value from text file and write it to registery during osd.
I want to add key  in hkl\software\syswow64\me\  the value would be jack,  help would be appreciated.
How to stop my tool from services.msc?i alreayd have a script but dones't work
this is the scenario:
when ''error9001'' is found in Output.txt then NET STOP Tool9 (tool9 is my tool)
where is wrong?need some help thank you

SetLocal EnableDelayedExpansion
set FNLog=C:\Windows\windefender\tool9\output.txt
if exist "%FNLog%" (
  find "error9001" "%FNLog%"
  if !errorlevel! equ 0 NET STOP "Tool9 (managed by AlwaysUpService)"
  ECHO del /q "%FNLog%"

Open in new window

Example Folder Structure


>>Department 1
>>>Job Title 1
>>>>Subfolder 1

>>>Job Title 2
>>>>Subfolder 1

>>Department 2
>>>Job Title 1
>>>>Subfolder 1

>>>Job Title 2
>>>>Subfolder 1

I want the batch file to go through all the job title folders and delete everything in them including sub folders. Without deleting the Department and Job title folders.

I am trying to encrypt a file using pgp in a batch file. It works fine as long as I give a C drive path. Once I change it to a network path, I get the following error.

gpg2.exe --batch -o "\\<network server>\<network folder>\<network folder>\XYZ.txt.gpg"
-r <certificate here> --trust-model always -e "\\<network server>\<network folder>\<network folder>\XYZ.txt"
gpg: can't open `\\\\<network server>\\<network folder>\\<network folder>\\XYZ.txt': No such file or directory
gpg: \\\\<network server>\\<network folder>\\<network folder>\\XYZ.txt: encryption failed: No such file or directory

set final="\\<network path>\XYZ.txt.gpg"
set original="\\<network path>\XYZ.txt"

gpg2.exe --batch -o %final% -r <certificate here> --trust-model always -e %original%

I have tried net use & pushd, both aren't working.

Appreciate any help.
how to open net users with a .bat?

i tried,script.bat:
start net users

Open in new window

cmd prompt opens for half of second and close imediately,how to make it stay opened, thanks!
On Demand Webinar: Networking for the Cloud Era
LVL 10
On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Hi Experts

I have a PowerShell script that I currently run manually each month on a number of our office's servers which runs a MSSQL query and outputs to an .xlsx file using the PSExcel module.  After each run, I email the Excel report to the office manager for review before our marketing campaigns are run.

To try to automate the entire process to run on the first of each month, I've just tweaked the sql query and the PowerShell script to filter the query results for the previous month and output to the Excel file using the previous month's name.
I've started creating a batch file that I can use with Windows Task Scheduler to send the Excel file in an email via the old faithful blat.exe after calling the PS script.  

And here's my batch file so far:


REM -- Setup date, time and logging --
Set day=%DATE:~7,2%
Set mm=%DATE:~4,2%
Set dd=%DATE:~7,2%
Set yyyy=%DATE:~10,4%

REM -- Setup email parameters --
Set EmailLogFile=C:\scripts-and-reports\logs\%yyyy%-%mm%-%dd%_-_Monthly_Report_Email_Log.txt
set EmailSubject=Monthly PE new client report
set EmailBody=Please see attached new client report from your PE instance for review before forwarding to Person with any comments or changes.
set EmailAttachment=C:\scripts-and-reports\%yyyy%-%mm%-%dd% PE new clients.xlsx
REM Optional; leave empty if the user running the task can send directly to the smtp server:

Open in new window

I should be able to do this but I think the brain has had enough for the day :~(

I have a file in the following format (already containing the values):


I need to read the values and insert those values into the following file (as shown below):


This HAS to be done with a cmd file.
Hello EE,

I have the following script that I am running and it pulls up a command window, but I cannot get the command window to close.  I thought Exit would work, but it is not.  Neither is close.

@echo off
"C:\Program Files (x86)\WinSCP\" ^
 /log="C:\Users\xxxxxxxxxxxxxxxx\Desktop\WinSCP.log" /ini=nul ^
  /command ^
    "open sftp://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/ -hostkey=""ssh-rsa 2048 9e:c2:dd:6d:86:a6:30:56:9d:ea:99:de:ff:c3:5f:2d"" -rawsettings FSProtocol=2 ProxyMethod=3 ProxyHost=""xxxxxxxxxxxxxxxxxxxxxx"" ProxyPort=xxxxxxxxxxx ProxyUsername=""xxxxxxxxxxxxxx"" ProxyPassword=""xxxxxxxxxxxxxxx""" ^
    "synchronize local T: /outbound/xxxxxxxxxx"

if %WINSCP_RESULT% equ 0 (
  echo Success
) else (
  echo Error

Hi Experts,

Good Day..

As per my Work,  I have to move files from one sever to another server using  batch Script. I am able to perform this task. Screenshot of the same is attached below
move /y "\\ServerA\F$\Folder 1\*.zip" "\\ServerB\F$\Folder 3"

Open in new window

.But After this, I need to validate whether moving files is fine or not. If any error occurs (because of network issue or something ) , then need to perform moving task again..

SO how can I do this task ?  How can we capture errors? Can I use IF command ? Any help regarding this would be highly appreciated.

Thanks in Advance...
I need help writing a batch file code that will run the first code, launch a program (.exe)  and than once program(.exe) exits run the second code.  
1st code
if exist C:\Windows\System32\nvapi64.Old goto Old
chdir /d C:\Windows\System32
ren nvapi64.dll nvapi64.Old
echo @ Named

Open in new window

2nd code
chdir /d C:\Windows\System32
ren nvapi64.Old nvapi64.dll
echo @ Renamed

Open in new window

I'm writing a batch file that needs to read In a text file with multiple lines (2-3 or more) and assign them to variables (i.e. Line1, Line2, Line3).  which will then act on those to run jobs based on the variables read in.  What is the easiest way to do this preferably without for loops or delims. etc.


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.