Wednesday, February 21, 2007

Cool options of the FOR command

The for command allows you to do a lot of cool stuff.

This is what most people use this command for, do stuff for some files or folders in a specific location.
for /D %%v in (*.*) do echo %%v

But did you know you can use this command to interpret comma delimited (csv) files?Display input.txt line by line:
for /F %%v in (input.txt) do echo %%v

Display 3 seperate values delimited by comma's
for /F "tokens=1-3 delims=," %%v in (input.txt) do echo %%v - %%w - %%x

Display first and third value
for /F "tokens=1,3 delims=," %%v in (input.txt) do echo %%v - %%w

Skip line 1
for /F "tokens=1-3 skip=1 delims=," %%v in (input.txt) do echo %%v - %%w - %%x

Why is this cool? Well, you could use it to generate homedirs for users, share the folder and grant the right permissions like this:
@echo off
if %1v==mv goto MAKE
for /F "skip=1 tokens=1" %%v in (users.csv) do call homedir3.cmd m %%v
goto end
md E:\Users\%2
net share %2$=E:\Users\%2 /grant:everyone,full
cacls E:\Users\%2 /E /G %2:C

This script will interpret users.csv and create homedirs for all the users in there. The file uses the same layout as you would use with AddUsers. It even skips the first line so you don't need to change anything in here. You need to save the script as homedir3.cmd as it calls itself to really do something.

No comments: