简体   繁体   中英

execute batch file when dropped in a specific folder

I have a need to execute a batch file when I drop it into a specific folder of one of my Windows PCs.

We have 20 PCs spread out thruout the US. I can remote into each PC and execute the batch file on the local PC but that takes a long time.

I can also do a file transfer into each of these PCs very quickly. If I can get the batch file to execute once it is placed in a specific folder that would solve my problem.

I've heard of listeners in the past. Where "something" on the PC is just looking at the contents of a folder. If a file happens to exist in that folder the listener executes "something".

Here's some pseudocode to help get a better understanding:

\\Program watches the contents of C:\Folder1
If 
   file batchfile.bat exists in C:\Folder1
     then execute batchfile.bat and then delete batchfile.bat

Else
   continue watching C:\Folder1 for batchfile.bat

I'm digging around SO and looks like PowerShell is going to be the path I need to take. Do you guys agree or is there a more efficient solution?

I am pretty sure powershell is not what you are looking for. While I would recommend powershell in place of batch for your payload, it is not ideal for these kinds of scheduled tasks.

Instead I would recommend one two paths:

  • If you can live with a delay, a batch or powershell script can be run every so often that checks a given folder, and runs anything it finds.
  • If you want instant gratification, a Windows service is the way to go, as it will run all the time and can easily handle the listener in this fashion.

Here's how I'd do it:

param([switch]$install)

$batchfile = "C:\Folder1\batchfile.bat"

if($install)
{
    invoke-expression ("schtasks -create -tn `"Job1`" -tr `"powershell -file '" + $myinvocation.mycommand.path + "'`" -sc DAILY -st 05:00 -rl HIGHEST -ru SYSTEM")
}
else
{
    if(test-path $batchfile)
    {
        cmd /c batchfile.bat
        remove-item $batchfile | out-null
    }
}

Run the above script with the "-install" switch and it will create a scheduled task to run once a day at 5:00am. If you'd like it to run more often check the syntax for schtasks to change that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM