« Strange File - FlushServ.exe | Artsy Ken, AKA Ken Lee's Photography »

Sample Script - Convert a text file to a system variable

When running a batch script there are times when you want to take the output of a utility and/or file and convert it to a system variable. Batch was not designed for this, but there's an easy way to do it....

In this example, we'll take a line of output from Systernals PSInfo.exe and convert it to a variable.


::REM ------------------ start batch sample script -------------------------------
::REM by John D. Seaman, www.japan-page.net/batch

::REM Call www.systernals.com psinfo.exe, put results in a text file

::REM Get output from psinfo to text file "_out.txt"
psinfo.exe >_out.txt

::REM Use find, isolate the Product Version line
type _out.txt | find "Product version:" _out2.txt

::REM Create a loop, grab the 2nd field (AKA the version)
::REM Tokens states we're looking at 2 values (and grabbing the second)
::REM Delims states break the string at the colon
::REM If you call this directly from the command line, change %%i below to %i.

for /f "tokens=1,2* delims=:" %%i in (_out.txt) do set var=%j

echo Your new variable VAR is %var%

::REM ------------------ end batch sample script -------------------------------

So, a simple for loop takes a value from a text file and converts this into a variable. What can you do with this? I have run some rather complex scripts such as dumping every workstation name in a 3000 user environment from AD, then calling a script against all the workstations to do some maintenance - check AV signatures in an outbreak, scan for disk space, verify a service is running, etc. With the for loop, you can process each machine, find the value your looking for, then dump the results into a log file or continue processing based on the result.

You can also use a 3rd party text manipulator such as SED (a GNU *Nix tool), or my old fav TextTools32 (t.exe), but the above trick will let you do it from the native windows command line.

Post a comment

(If you haven't left a comment here before, you may need to be approved by the site owner before your comment will appear. Until then, it won't appear on the entry. Thanks for waiting.)