System / Environmental Variables can be useful creatures to deal with at times, especially if you have an IT Department that actually takes the time to define custom variables specific to your environment. For most of us that's not the case, but even the "out of the box" variables can be a quick source of useful data.
There are a couple of ways to work with System Variables, the method of which depends greatly on your personal preference and whether or not you already know that a particular variable exists. If you know it's name and know it's there, then you can get the value with just a few lines of code. For a System Variable with a name of COMPUTERNAME you'd use the following.
Set wS = WScript.CreateObject( "WScript.Shell" )
strComputerName = wS.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
strComputerName will contain the current value of the variable.
A quick, easy way to tell if the System Variable exists on the machine? Use the same method above and then check the value of strComputerName. If the variable is not defined on the system the value will be the name passed to wS.ExpandEnvironmentStrings(), % signs and all!
Of course I've also occasionally wanted to know what system variables are actually available for use on a machine, without playing hide-and-seek in the dark with the above method. If you're interested in generating a list of all of the available variables then use something like the following.
'----------------------------------------------------------------------
'---Optional---
Set Worker = New Logger
'---Optional---
strComputer = "."
Set objWMI = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colI = objWMI.ExecQuery("Select * from Win32_Environment")
For Each objI in colI
'Your code here, the example below outputs the list to a file
'---Optional---
Worker.logThis("Name: " & objI.Name & " : " & "Value: " & objI.VariableValue)
'---Optional---
Next
'---Optional---
Class Logger
Sub logThis(txtString)
Set objFSO = Createobject("Scripting.FileSystemObject")
objLogFile = Left(wscript.scriptname, Len(wscript.scriptname)-4) & "_Log.txt"
Set objfile1 = objFSO.OpenTextFile(objLogFile, 8, True)
objfile1.Write txtString
objfile1.Writeline
objfile1.close
end sub
end class
'---Optional---
'----------------------------------------------------------------------
For the full list of available attributes for a Win32_Environment object, search for "Win32_Environment" or go here
Win32_Environment on MSDN
Cheers,
No comments:
Post a Comment