.bat file - How to start a .bat file when I rename any file in a specific folder - batch-file

I want my .bat file to run after I rename a file in the Sources folder that is located here:
C:\Users\UserName\Videos\Gameplays\HeroesOfTheStorm\Sources\
The .bat file is located in the same Sources folder.
How can I do that without double-clicking on the .bat file manually? I want it to run automatically after I rename a file in the Sources folder.

Set WshShell = WScript.CreateObject("WScript.Shell")
Set WMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set MonitoredEvents = WMI.ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""C:\\\\Users\\\\David Candy""'")
Do
Wscript.Echo MonitoredEvents.NextEvent.TargetInstance.PartComponent
WshShell.Run "cmd /c ""C:\folder\batchfile.bat""", 1, false
Loop
Note the use of 4 \ for 1 in directory name but nowhere else.
It a vbs file. It monitors a directory and will run commands if you rename or create files in that directory. WITHIN 10 means it tests every 10 secs.
Set WshShell = WScript.CreateObject("WScript.Shell")
Set WMI = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set MonitoredEvents = WMI.ExecNotificationQuery("SELECT * FROM __InstanceCreationEvent WITHIN 10 WHERE Targetinstance ISA 'CIM_DirectoryContainsFile' and TargetInstance.GroupComponent= 'Win32_Directory.Name=""C:\\\\Users\\\\David Candy""'")
Do
WMIPath = Split(MonitoredEvents.NextEvent.TargetInstance.PartComponent, "=")(1)
FilePath = Replace(WMIPath, "\\", "\")
WshShell.Run "cmd /k echo File Renamed is " & FilePath & "&" & Filepath
Loop

Ok, you can do this in a rather complicated way with windows tools.
First, you need to enable Auditing.
run GPEDIT and then go to: Computer Configuration --> Windows Settings --> Security Settings --> Local Policies --> Audit Policy --> Audit object Access
enable i guess both success and failures.
Now go to the folder you want to monitor, double-click and go to: security tab --> Advanced --> Auditing Tab
add a rule with your user (or a groups or something like that) that will make a log for the rename (the is no rename event, but you can try different combination, like file creation, file delete or read/write attributes you can find)
after that, now if you got to Event Viewer, Security log, a couple of events with Ids 4565/4663 will appear when the operation you selected is perfomed.
last thing, open the Task Scheduler and create a new task, with the activation set to the trigger of the event and an action that will run the bat.
Some of the term may differ, my Windows is not in English so i might have translated something wrong. Also, you might do some tests to see if you have everything set up correctly.
Another option might be setting up a small application that monitors the folder and run the bat accordingly. You can do such a thing in Java or in other languages.

This can be achieve easily with AutoHotkey using WatchDirectory()
https://stackoverflow.com/a/30582696/883015

Related

Passing an argument into a VBS script which passes into a batch file

I have a legacy application which doesn't support utilizing the default applications defined in windows which requires that I specify a specific an executable for a file format to be opened within the application. Since Microsoft no longer includes MODI with Office by default I have been looking at using launching Windows Picture Viewer for .TIF, .TIFF, & .BMP files since it is built into Windows; however Microsoft does not have a direct executable for Windows Picture Viewer which can be called forcing me to create a script which executes the command which calls for Windows Picture Viewer to execute. After research the only way I have been able to call the application to open a specific file is by creating a batch file such as below:
GIFTS.BAT
rundll32.exe C:\WINDOWS\system32\shimgvw.dll,ImageView_Fullscreen %~1
If I execute the above code such as GIFTS.BAT "C:\Example Directory\Sample File.tif" from a command prompt or from the application launches and the Sample File.tif opens without a problem; however a command prompt opens along with the file when launching from the application.
Upon which I tried to create a vbscript to hide the batch file from executing however I can't seem to pass my argument if the argument has a "space" within the argument.
GIFTS.VBS
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run """C:\GIFTS.BAT"" " & WScript.Arguments.Item(0), 0
Set WshShell = Nothing
If I try to execute the VBScript from a command prompt such as GIFTS.VBS "C:\Example Directory\Sample File.tif" the application never launches and the command prompt returns no message or error. If I simplify the execute command (removing spaces to GIFTS.VBS "C:\Sample_File.tif" the application launches as well as the file Sample_File.tif is displayed and there is no command prompt displayed when the application executes the VBScript.
My question is how can I pass an argument into the VBS script that in return passes the the batch file when the argument contains spaces (which there is always going to be spaces since the argument will be a file name and path)?
There might be an easier approach to what I want to accomplish; however I am looking for a solution that Windows 7 - 8.1 can utilize with no additional software to install or manage on each workstation. The batch files works great I just need to be able to hide the command prompt that opens along with the application as my end users won't know what to do with it.
Thanks!
Sometimes, nested levels of escaping characters requires intimate knowledge of the undocumented behavior of CMD or some voodoo. Another way to attack the problem is to guarantee that you won't have any spaces in the name of the file. Windows has a concept of a short path (no spaces or special chars) for which every existing file has a unique one.
Here's a modified version of your program for which invoked subcommand doesn't need quotes around the file name.
Set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Set fsoFile = fso.GetFile(WScript.Arguments.Item(0))
WshShell.Run """c:\GIFTS.BAT"" " & fsoFile.ShortPath, 0
Set WshShell = Nothing
You may wish to add your own error checking. The specified file must exist in order for the GetFile() command to succeed.

Batch file to open specific folders in specific window position

I have a batch file that opens 3 specific folders, but I want the batch file, if possible, to show the windows side by side.
Consider using VBS(Visual Basic Scripting) for this job.
You can easily arrange the open windows in common ways like: Cascade, TileHorizontally, TileVertically, etc.
For example, the following script will open three specific folders and then tile horizontally the open windows on screen:
Dim shell
Set shell = CreateObject("Shell.Application")
shell.Open "path_folder1"
shell.Open "path_folder2"
shell.Open "path_folder3"
Wscript.Sleep 1000
shell.TileHorizontally
Of course, you can also open the folders from the batch and then call a .vbs script to arrange the windows.
EDIT:
To arrange in the screen only the specific opened windows, we can first minimize all present windows, then do the job:
Dim shell
Set shell = CreateObject("Shell.Application")
shell.MinimizeAll
shell.Open "path_folder1"
shell.Open "path_folder2"
shell.Open "path_folder3"
Wscript.Sleep 1000
shell.TileHorizontally
However, if you want to keep old windows active in the same position they was before and at the same time to arrange ONLY new windows, i don't have a solution right now.

Batch File To Get It's Own Directory Or The Directory Defined In The "Start In" Property Of A Shortcut

I am writing a batch file on my Windows 8.1 machine. In one section of my batch file I need to start a command prompt in the "current working directory".
So far, this is what my batch file looks like:
#echo OFF
set WORKING=%cwd%
start cmd.exe /K pushd %WORKING%
exit
Let's say the batch file is located in the folder C:\Temp\Utilities. If I open an explorer window and double click the batch file to run it everything works great. A new command prompt is created in the directory C:\Temp\Utilities. However, if I right-click the batch file and select Run as administrator the working directory is no longer the location of the batch file, it's C:\Windows\System32.
Similarly, if I create a shortcut to the batch file in a different folder (for example. C:\Temp) and repeat the two steps above the results are the same. If I double click the shortcut and run it as a normal user the working directory is what I would expect. (Note, the working directory for the shortcut it's whatever is set for "Start in" of the shortcut properties, not the location of the batch file.) If I right click the shortcut and run it as administrator I again get a command prompt opened to the folder C:\Windows\System32.
I assume this is a "bug" or "feature" (if you want to call it that) in Windows 8.1 and it probably happens because execution environments for programs run as administrator are forced to run in the System32 folder? (I remember with Windows 7 this did not happen so it must be a new feature to Windows 8.)
I found one way to fix the issue and stop the command prompt from starting in C:\Windows\System32. I did this by modifying the following line in the batch file:
set WORKING=%~dp0
Doing it this way sets the working directory to the location of the batch file. With this change, no matter how I run the batch file or the shortcut (administrator or normal) the working directory ends up being the same, C:\Temp\Utilities.
The problem with this solution is I don't want the working directory to always be the location of the batch file. If the batch file is run directly then it's okay but if I run it from a shortcut I need the working directory to be whatever is set in the "Start in" property of that shortcut. For example, if the batch file is located in the folder D:\Temp\Utilities this is what I need to happen regardless of whether I run as administrator or not:
Shortcut Location Start In Property Command Prompt Working Directory
-------------------- ------------------- ------------------------------------------
C:\Temp <undefined> D:\Temp\Utilities
C:\Data\bin C:\Data\bin C:\Data\bin
C:\Data\bin D:\Temp\Utilities D:\Temp\Utilities
What this means is I can't always use %~dp0 to set the working directory in my batch file. What I need is some way for the batch file to know if it was run either directly or by a shortcut. If the batch file is run directly then the working directory is easy to get, it's just the value of %cwd%. If the batch file is run by using a shortcut, I don't know how to get the "Start in" property inside the batch file.
Does anyone know how I can do these two things inside my batch file:
1. Check whether it was run directly or by a shortcut.
2. If run by a shortcut, get the "Start in" property of the shortcut that started it.
Thank you,
Orangu
UPDATE
I found sort-of a "hackish" way to fix the issue. For the shortcut I edited the "Target" field and changed it to the following:
cmd.exe /k pushd "C:\Temp" && "D:\Temp\Utilities\batchfile.bat"
Now the working directory can be obtained by calling %CD% in the batch file and this works for both administrator and normal users. It does not, however, work for the case when I run the batch file directly. I still need to use %~dp0 in that case.
I don't like this solution, however, because it requires me to manually change all shortcuts I make and it also makes the icon look like a cmd prompt icon rather than a batch file.
Have you already considered to not use shortcuts at all?
You could e.g. create a batchfile_exec.bat containing your call
REM optionally do
REM cd /D working_directory
REM if you want to force a special working directory
D:\Temp\Utilities\batchfile.bat
and replace all the shortcuts with batchfile_exec.bat. If you double-click batchfile_exec.bat, the working directory will be the one containing batchfile_exec.bat.
I personally don't like Windows shortcuts that much, because they are hard to handle within a revision control system. As you also noticed, it is very time consuming if you want to modify a lot of them.
By the way: If batchfile.bat was designed/written to be always run from the direcory where it is located, you might also consider to modify batchfile.bat to force that behaviour:
setlocal
cd /D %0\..
REM your original content
endlocal
In %0 the path to the batchfile is stored.
The trick is to assume that %0 is a directory and then to change one level lower based on that directory. With /D also the drive letter is changed correctly.
The cd command doesn't care if %0 is really a directory. In fact %d doesn't even have to exist (%0\dummy\..\.. would also work).
The setlocal command is to have the working directory being restored when batchfile.bat has finished (this would be good if batchfile.bat was called form another batch file).
I noticed that the endlocal command is not really necessary in this context since it is applied implicitly when batchfile.bat finishes.

Run Batch File On Start-up

Is there a way to start multiple programs in a batch file on system start-up? In addition to that, in that batch file, I would like to be able to say: Once I execute a program, wait until that program completely loads, and execute the next listed program.
Any help would be appreciated.
I had the same issue in Win7 regarding running a script (.bat) at startup (When the computer boots vs when someone logs in) that would modify the network parameters using netsh. What ended up working for me was the following:
Log in with an Administrator account
Click on start and type “Task Scheduler” and hit return
Click on “Task Scheduler Library”
Click on “Create New Task” on the right hand side of the screen and set the parameters as follows:
a. Set the user account to SYSTEM
b. Choose "Run with highest privileges"
c. Choose the OS for Windows7
Click on “Triggers” tab and then click on “New…”
Choose “At Startup” from the drop down menu, click Enabled and hit OK
Click on the “Actions tab” and then click on “New…”
If you are running a .bat file use cmd as the program the put
/c .bat
In the Add arguments field
Click on “OK” then on “OK” on the create task panel and it will now
be scheduled.
Add the .bat script to the place specified in your task event.
Enjoy.
To run a batch file at start up: start >> all programs >> right-click startup >> open >> right click batch file >> create shortcut >> drag shortcut to startup folder.
The path to the folder is : [D|C]:\Profiles\{User}\‌​AppData\Roaming\Micro‌​soft\Windows\Start Menu\Programs\Startu‌​p
Go to Run (WINDOWS + R) and
Type
shell:startup, paste your .bat file there !
To start the batch file at the start of your system, you can also use a registry key.
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
Here you can create a string. As name you can choose anything and the data is the full path to your file.
There is also the registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce
to run something at only the next start of your system.
There are a few ways to run a batch file on start up. The one I usually use is through task scheduler. If you press the windows key then type task scheduler it will come up as an option (or find through administerative tools).
When you create a new task you can chose from trigger options such as 'At log on' for a specific user, on workstation unlock etc. Then in actions you select start a program and put the full path to your batch script (there is also an option to put any command line args required).
Here is a an example script to launch Stack Overflow in Firefox:
#echo off
title Auto launch Stack Overflow
start firefox http://stackoverflow.com/questions/tagged/python+or+sql+or+sqlite+or+plsql+or+oracle+or+windows-7+or+cmd+or+excel+or+access+or+vba+or+excel-vba+or+access-vba?sort=newest
REM Optional - I tend to log these sorts of events so that you can see what has happened afterwards
echo %date% %time%, %computername% >> %logs%\StackOverflowAuto.csv
exit
RunOnce
RunOnce is an option and have a few keys that can be used for pointing a command to start on startup (depending if it concerns a user or the whole system):
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce
setting the value:
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v MyBat /D "!C:\mybat.bat"
With setting and exclamation mark at the beginning and if the script exist with a value different than 0 the registry key wont be deleted and the script will be executed every time on startup
SCHTASKS
You can use SCHTASKS and a triggering event:
SCHTASKS /Create /SC ONEVENT /MO ONLOGON /TN ON_LOGON /tr "c:\some.bat"
or
SCHTASKS /Create /SC ONEVENT /MO ONSTART/TN ON_START /tr "c:\some.bat"
Startup Folder
You also have two startup folders - one for the current user and one global.
There you can copy your scripts (or shortcuts) in order to start a file on startup
::the global one
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
::for the current user
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
1. Copy the following lines to Notepad.
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Users\toto\your_file.bat" & Chr(34), 0
Set WshShell = Nothing
Note: Replace the batch file name/path accordingly in the script according to your requirement.
2. Save the file with .VBS extension, example launch_bat.vbs
3. Create new .bat file, in our case your_file.bat
4. Write the content of your .bat file.
Example:
#echo off
php c:\laragon\www\my_app\artisan serve --host=127.0.0.1 --port=8000
5. Run your_file.bat and ejoy :)
If your Windows language is different from English, you can launch the Task Scheduler by
Press Windows+X
Select your language translation of "Computer Management"
Follow the instruction in the answer provided by prankin
Another option would be to run the batch file as a service, and set the startup of the service to "Automatic" or "Automatic (Delayed Start)".
Check this question for more information on how to do it, personally I like NSSM the most.

How could you edit a specific group policy using a batch file

Im working on over 700 computers in a school district and have written a small program that i intend to write to a cd. The program is set to autorun when the disk is inserted and prompt the screen resolution of the computer and what computer the building is in (the different school buildings). Afterwards the program will run a batch file that copies a default desktop from the disk and into the windows\web\wallpaper directory. It also replaces other files that have been customized for the school district.
To finish changing the theme of the computer, i need to have the file make a few edits to the group policy and the registry. How would i be able to use the program to makes these changes? Would it all be written into the batch or would the batch have to initiate another file (like a registry file)?
All the group policy editor does is set registry keys. If you can identify what keys are being set for the policy you want, you can use reg.exe to set those keys.
reg.exe add HKCU\Software\path\to\regkey\ /v valuename /d newvalue
Registry will work for the first user, but after a new user logs in, GP will change those settings for the new user.
To make deployment gp, do this: Set one machine's GP to the way you want it. Once you are done, goto C:\windows\System32\GroupPolicy and copy the contents. (note: this is a hidden file). On the next machines you want, just paste back in the file.
If you do this in a batch, you will have to run the batch as administrator to touch the C:\windows\system32 folder. (UAC, the bane IT)

Resources