Subscribe to Windows IT Pro
March 19, 2001 12:00 AM

Command Output in a Variable

Windows IT Pro
InstantDoc ID #20029
Rating: (1)

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=%%I
For /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 ('<any command>') Do Set <variable name>=%%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

Related Content:

ARTICLE TOOLS

Comments
  • Bruce Heimbigner
    8 years ago
    Feb 05, 2004

    InstantDoc #20029 The script won't run. The value of the Variable StrTime has colons in it, which are not allowed in filenames. Try this (in batch file):
    For /F "tokens=1,2,3 delims=:" %%I in ('now') Do set FileName=%%I.%%J.%%K

You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement

advertisement

Windows is a trademark of the Microsoft group of companies. Windows IT Pro is used by Penton Media Inc. under license from owner.