Windows – clear out the same directory on multiple servers across a network. How to do this

batchbatch-filewindows

On multiple (about 20) servers, there exists the same directory C:\Deployments. This directory has multiple subfolders which contain more subfolders and files. The C:\Deployments directory itself does not contain files.

I have a batch file that, when run locally, cleans out the C:\Deployments directory. That is, it deletes all subfolders and their files, but doesn't delete the C:\Deployements directory itself.

The batch file code is:

echo off

set CAT=c:\deployments

dir "%%CAT%%"/s/b/a | sort /r >> %TEMP%\files2del.txt 
for /f "delims=;" %%D in (%TEMP%\files2del.txt) do (del /q "%%D" & rd "%%D") 
del /q %TEMP%\files2del.txt

My question is this:

How do I run this batch file on each server from a localized window? That is, how do I run one batch file and have these commands execute on every server simultaneously?

Thanks for any help/ideas!

Best Answer

I don't have a Windows machine anymore, but used to do this stuff at work. There is psexec which allows you to remote to another server. You can also look into powershell remoting.

Powershell Remoting see http://msdn.microsoft.com/en-us/library/windows/desktop/ee706585(v=vs.85).aspx

Using Dos / Batch, see http://ss64.com/nt/psexec.html

If you want them to run simultaneously, you can do this, by running jobs in powershell, see the same ss64 site.

If you are interested...

If your servers are listed in active directory, you can do a little trick where you say loop through computers using Active Directory

dsquery computer -limit 0 | ?{$_ -imatch "CN=([^,]+),"} | % {
  #remotely run your script here through ps remote
}

or replace dsquery... with gc $your_file_name containing list of files. Dos/Batch - my syntax may be off, but this is a nice way to loop over computers

for /f "eol=, tokens=1, delims=" %cc in ('dsquery computer -name -limit 0 ^| find /i /r /c:'"CN=([^,]+),"') do (

  @REM cannot recall how i used to get back references in dos like this, so may be off.
  @REM call your script here, passing your batch program to psexec
  set computer=%%c
  echo computer=!computer!
)

or replace dsquery... with type "%your file name%"

Also, if you ever run into a problem setting variables within a loop in batch where they do not persist as you would expect, place setlocal enabledelayedexpansion at the top of your program, and evaluate your variables like this !var_name! instead of %var_name%