Carl's blog

for %a in (param1 param2 ..) do something with %a

by on Dec.11, 2010, under Computer Stuff

This is useful. The params can be a filespec, e.g. “*.pdf”, or they can just be values given on the command-line.

Let’s say you are remotely accessing a computer, and you want to release and renew its IP address. When you release the IP address, you’ll lose connectivity and won’t be able to renew. You could make a batch file, or you could do:

for %a in (release renew) do ipconfig /%a

This will run “ipconfig /release” followed by “ipconfig /renew”.

Or let’s say you have a thousand home directory folders, and you set the permissions a bit wrong. You want each user to have full control of their own folder. You could do:

for /D %a in (*) do cacls %a /E /G %a:F

This will run “cacls carl.farrington /E /G carl.farrington:F”, substituting carl.farrington for the folder name and user name until every folder has been done. This example assumes of course that the folder name is the same as the user name who you want to grant the permissions to. Notice the /D – this means the filespec matches directory names, not filenames. Without the /D the * would not return any directory names.

Another example. You might want to search within every .ini file in the current directory. NT’s “find” command doesn’t accept wildcards/multiple files. So what you do is use a for loop and pipe the output into a text file that you can check when the process completes:

for %a in (*.ini) do find /i “Microsoft” %a >>output.txt

This will do “find /i “Microsoft” file1.ini >>output.txt”, then file2.ini, then file3.ini. You can check the output of output.txt to see which files contained the text you were searching for.

I sometimes use this to search all the oem*.inf files in %windir%\inf to find the inf file that’s supplying driver information for a particular piece of hardware. Then I can delete that inf file, remove the hardware from device manager and Windows will not just re-install the existing driver for the device, allowing you to supply a different driver. Searching for the INF file is not necessary on Vista because the details tab in a device’s properties within Device Manager has been extended to display the inf source.

Comments are closed.

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!


A few highly recommended websites...