Command Output in a Variable
One reader shares his tips for using batch files to generate filenames that include date or time information.
March 18, 2001
I use command scripts to perform various administrative tasks—generating files that contain date- or time-related data is often useful. A simple way to generate a filename that includes date or time information is to include the following lines in batch files:
For /F "Tokens=2" %%I in ('Date /T') Do Set StrDate=%%IFor /F "Tokens=*" %%I in ('Time /T') Do Set StrTime=%%I
These commands assign the date to a variable, %StrDate%, and the time to a variable, %StrTime%, which you can use for subsequent batch processing, as the following command shows:
Dir C:*.* /S /B >> %Temp%%Computername%_%StrDate%%StrTime%.Log
By changing the For statement's syntax, you can adjust the %StrDate% and %StrTime% variables so that you can get the format of information you require.
You can also use this method to assign any type of command output to a variable:
For /F "Tokens=2" %%I in ('') Do Set =%%I
For example, the following command redirects the output of a Ping command to %StrServer% in the variable %StrAnswer%:
For /F "Skip=3 Tokens=*" %%I in ('ping %StrServer% -n 1') Do Set StrAnswer=%%I
—David England
[email protected]
About the Author
You May Also Like