Non Sequitur: Creating Dynamic Variables on the Fly in Batch

I’m only mentioning this because of something that came up recently and I thought it was kind of neat.

To keep things simple, I’m going to break this up into a few posts:

  1. Batch
  2. VBScript
  3. PowerShell

 

Batch

Maybe 5 years ago, before I dunked my head into the vat of PowerShell Kool-Aid™ (or is it ­®?), I was doing some work in the registry on various machines to get some specific data.  I thought it would be neat to create a function that would allow me to reference the data by calling on the value name.

I came up with this little number:

@echo off
setlocal enabledelayedexpansion

rem This happens to be Microsoft Visual C++ 2010 x64 Redistributable - 10.0.40219 - everyone has that ! 😉
Set _Key=HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
Set _QueryValues=Publisher DisplayName DisplayVersion InstallSource

rem execute to generate variables dynamically
For %%b in (!_QueryValues!) do ( for /F "usebackq tokens=2*" %%c in (`reg query "!_Key!" /v "%%b"`) do (set %%b=%%d) )

rem validate dynamicallly generated variables
For %%e in (!_QueryValues!) do ( echo [%%e] is [!%%e!] )

:end
rem clear dynamically generated variables
For %%e in (!_QueryValues!) do (Set %%e=)
set _QueryValues=
set _Key=
endlocal
pause

Which allowed me to do things like this:

echo Publisher is [!Publisher!]
echo DisplayName is [!DisplayName!]
echo DisplayVersion is [!DisplayVersion!]
echo InstallSource is [!InstallSource!]

Throughout the script wherever I needed to reference one of those varaibles.

Worked like a charm for my needs then and I still think it’s pretty slick.

 

Good Providence!

Advertisements

One comment

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s