Unattended Install and Upgrade of Adobe Reader

Previously we explored how to increase the success rate of unattended application upgrades using our handy “killAndExec” VBScript. This works well for about 80% of our applications. What about Adobe Reader? Well… not so much.

Thankfully, the stock Adobe Reader installer deals with open files quite nicely, and does not care if Reader is in use by a browser during silent installs (this is the main reason that we needed killAndExec.vbs in the first place). However, not all Reader install operations are full installs. Interestingly, Adobe is one of the few vendors that I deal with that actually uses MSI patch files (MSP). To install a patch release of Reader (i.e. 10.1.4), you need first to install the base version (10.1), then one or more patch MSP files. This is easy for new installs… just run “setup.exe” silently, then run “msiexec /p (patchFileName) /qn” to install the patch.

However, the situation gets more complicated for upgrades. If the base product already is installed, setup.exe will return an error code. So, for upgrade scenarios, I have put together another handy VBScript to handle base version detection. The script follows:

option explicit
' Install Adobe Reader Script:
' J. Greg Mackinnon, 2012-06-12
' Intended to perform unattended installations of Adobe Reader by MS SCCM 2012.
' 
' Installs the version of Adobe Reader in the same directory as the script, if not already installed.
' Also installs the current Reader patch, if requested.
' Installer string is specified in "sInstall".
' Requires: 
'     Adobe Reader setup and patch files in the same directory as the script.
'     "setup" and "basever" arguments required.
'     "patch" argument optional.
' Returns:
'     - Code 100 - if required arguments are not provided to the script.
'     - Return code of setup program added to the return code of the patch program, if no other errors occur.

dim oExec, oFS, oLog, oShell
dim cScrArgs
dim iExit
dim sBaseVer, sInstall, sLog, sOut, sPatch, sPath, sPF, sScrArg, sTemp, sVer
dim bDoPatch

sLog = "installAdobeReader.log"
iExit = cLng(0)

' Instantiate objects:
Set oShell = CreateObject( "WScript.Shell" )
Set oFS = CreateObject("Scripting.FileSystemObject")
sTemp = oShell.ExpandEnvironmentStrings("%TEMP%")
Set oLog = oFS.OpenTextFile(sTemp & "" & sLog, 2, True)

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Define Functions
'
function echoAndLog(sText)
'EchoAndLog Function:
' Writes string data provided by "sText" to the console and to Log file
' Requires: 
'     sText - a string containig text to write
'     oLog - a pre-existing Scripting.FileSystemObject.OpenTextFile object
	'If we are in cscript, then echo output to the command line:
	If LCase( Right( WScript.FullName, 12 ) ) = "cscript.exe" Then
		wscript.echo sText
	end if
	'Write output to log either way:
	oLog.writeLine sText
end function

sub subHelp
	echoAndLog "installAdobeReader.vbs Script"
	echoAndLog "by J. Greg Mackinnon, University of Vermont"
	echoAndLog ""
	echoAndLog "Runs Adobe Reader silent setup (if not already present), then applies "
	echoAndLog "any specified MSP patch files for Reader."
	echoAndLog "Logs output to 'installAdobeReader.log' in the %temp% directory."
	echoAndLog ""
	echoAndLog "Required arguments and syntax:"
	echoAndLog "/setup:""[setupFile]"""
	echoAndLog "     The primary Adobe Reader installation program.  If switches "
	echoAndLog "    are required for setup to run silently, they must be provided."
	echoAndLog "/basever:"
	echoAndLog "     The base Adobe Reader product version for which to check (i.e. 10.1)"
	echoAndLog ""
	echoAndLog "Optional arguments and syntax:"
	echoAndLog "/patch:""[patchFile]"""
	echoAndLog "     MSP patch file to install after Adobe Reader setup completes."
end sub
' End Functions
'''''''''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Parse Arguments
'
if WScript.Arguments.Named.Count > 0 Then
	Set cScrArgs = WScript.Arguments.Named
'	For Each sScrArg in cScrArgs
'		echoAndLog sScrArg 'Echo supplied arguments to console
'	Next

	for each sScrArg in cScrArgs
		select case LCase(sScrArg)
			Case "setup"
				sInstall = cScrArgs.Item(sScrArg)
			Case "patch"
				sPatch = cScrArgs.Item(sScrArg)
			Case "basever"
				sBaseVer = CStr(cScrArgs.Item(sScrArg))
			Case Else
				echoAndLog vbCrLf & "Unknown switch or argument: " & sScrArg & "."
				echoAndLog "**********************************" & vbCrLf
				subHelp
				oLog.Close
				WScript.Quit(100)
		end select
	next
	if (IsNull(sInstall) or IsEmpty(sInstall)) then
		echoAndLog "Required argument 'setup' was not provided."
		echoAndLog "**********************************" & vbCrLf
		subHelp
		oLog.Close
		wscript.quit(100)
	elseif (IsNull(sBaseVer) or IsEmpty(sBaseVer)) then
		echoAndLog "Required argument 'basever' was not provided."
		echoAndLog "**********************************" & vbCrLf
		subHelp
		oLog.Close
		wscript.quit(100)
	elseif (IsNull(sPatch) or IsEmpty(sPatch)) then 
		bDoPatch = False
	else
		bDoPatch = True
	end if
elseif WScript.Arguments.Named.Count = 0 then 'Detect if required args are not defined.
	echoAndLog vbCrLf & "Required arguments were not specified."
	echoAndLog "**********************************" & vbCrLf
	subHelp
	oLog.Close
	WScript.Quit(100)
end if
'
' End Argument Parsing
'''''''''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Begin Main
'

' Complete version and installation strings:
sInstall = "." & sInstall
sPatch = "msiexec.exe /p " & sPatch & " /qb /norestart"

' Build path to Adobe Reader executable:
sPF = oShell.ExpandEnvironmentStrings( "%ProgramFiles%" )
sPath = sPF & "AdobeReader 10.0ReaderAcroRd32.exe"
echoAndLog "Acrobat Reader Path: " & sPath

' Get the version string on the currently installed Reader executable:
on error resume next
sVer = oFS.GetFileVersion(sPath)
on error goto 0
echoAndLog "Version of currently installer Adober Reader: " & sVer

' See if we already have the base version installed:
if InStr(Left(cStr(sVer),4),sBaseVer) then
	'Reader 10.1.x is already installed skip base product installation.
	echoAndLog "Base product installed.  Skipping setup..."
else
	'Install the base product.
	echoAndLog "Installing base product with command: " & sInstall
	set oExec = oShell.Exec(sInstall)
	Do While Not oExec.Status  1
		WScript.Sleep(100)
	Loop 
	sOut = oExec.StdOut.ReadAll()
	echoAndLog "Return code from installer: " & oExec.ExitCode
	echoAndLog "Standard output: " & sOut
	iExit = cLng(oExec.ExitCode)
end if

'Now install the patch:
if bDoPatch = True then
	echoAndLog "Patch installation requested."
	echoAndLog "Installing patch with command: " & sPatch
	set oExec = oShell.Exec(sPatch)
	Do While Not oExec.Status  1
		WScript.Sleep(100)
	Loop 
	sOut = oExec.StdOut.ReadAll()
	echoAndLog "Return code from patch installer: " & oExec.ExitCode
	echoAndLog "Standard output: " & sOut
	iExit = cLng(oExec.ExitCode) + iExit
else 
	echoAndLog "Patch installation was not requested.  Exiting."
end if

oLog.Close
wscript.quit(iExit)
'
' End Main
'''''''''''''''''''''''''''''''''''''''''''''''''''

Advertisements

KillAndExec.vbs – Ensuring application installer success with VBScript

Today’s scripting challenge…

We are attempting to use SCCM 2012 as a patch management solution for our centrally supported third party applications.  Great new features in SCCM 2012 allow us to write detection rules for applications to determine if superseded versions are present on the client system, and to trigger an immediate upgrade.  Cool Beans.  Problem is, a lot of application installers that ran reliably in our MDT “LiteTouch” environment (which is used to deploy new operating systems with no previously installed software) will not run silently or successfully on systems where previous application versions were already installed, and may currently be running.

This is an old problem for client system management… how can you update in-use files?  In most cases I have seen, the admin will schedule the updates to run when no one is logged in.  Unfortunately, this is an edge case for us.  Most systems are off when no one is logged in.  Another system is to force logoff for application updates.  While this would work, it seems like a “heavy” solution… why force the user to log off to update one application that may or may not be running?  Why force all applications closed on the off chance that one application will need to be terminated.

Our solution?  Kill only the processes that need to be terminated to ensure application installation success.  See the VBScript solution below (I flirted with writing this one in PowerShell, but the code signing requirements still intimidate me, and I may have the odd-duck XP client that still does not have PowerShell).  I have tested the script on Firefox, Thunderbird, VLC, Notepad++, WinSCP, Filezilla, and KeePass.  Rock On!

UPDATE: Since initial publication, I have added some logic to handle execution from “wscript”. If the script is executed from wscript.exe, console output will be suppressed. Additionally, the log file now is named “killAndExec-(exeFileName).log”. (This prevents SCCM from overwriting the log file the next time a program installer runs that also uses this script).

'KillAndExec.vbs script, J. Greg Mackinnon, 2012-09-13
' Kills processes named in the "kill" argument (comma-delimited)
' Runs the executable named in the "exec" argument
' Appends the executable arguments specified in the "args" argument (comma-delimited)
'Requires: "kill" and "exec" arguments.  The executable named in the "exec" arg must be in the same directory as this script.
'Provides:
' RC=101 - Error terminating the requests processes
' RC=100 - Invalid input parameters
' Other return codes - Pass-though of return code from WShell.Exec.Run using the provided input parameters

Option Explicit

const quote = """"

'Declare Variables:
Dim aExeArgs, aKills
Dim bBadArg, bNoArgs, bNoExeArg, bNoExec, bNoKill, bNoKillArg 
Dim cScrArgs
Dim iReturn
Dim oShell, oFS, oLog
Dim sBadArg, sCmd, sExe, sExeArg, sKill, sLog, sScrArg, sTemp

'Set initial values:
bBadArg = false
bNoArgs = false
bNoExeArg = false
bNoExec = false
bNoKill = false
bNoKillArg = false
iReturn = 0

'Instantiate Global Objects:
Set oShell = CreateObject("WScript.Shell")
Set oFS  = CreateObject("Scripting.FileSystemObject")

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Define Functions
'
Sub subHelp
	echoAndLog "KillAndExec.vbs Script"
	echoAndLog "by J. Greg Mackinnon, University of Vermont"
	echoAndLog ""
	echoAndLog "Kills named processes and runs the provided executable."
	echoAndLog "Logs output to 'KillAndExec.vbs' in the %temp% directory."
	echoAndLog ""
	echoAndLog "Required arguments and syntax:"
	echoAndLog "/kill:""[process1];[process2]..."""
	echoAndLog "     Specify the image name of one or more processes to terminate."
	echoAndLog "/exe:""[ExecutableFile.exe]"""
	echoAndLog "     Specify the name of the executable to run."
	echoAndLog ""
	echoAndLog "Optional arguments:"
	echoAndLog "/args""[arg1];[arg2];[arg3]..."""
	echoAndLog "     Specify one or more arguments to pass to the executable."
	echoAndLog "/noKill"
	echoAndLog "     Switch to suppress default process termination.  Used for testing."
	echoAndLog "/noExec"
	echoAndLog "     Switch to suppress default program execution.  USed for testing."
End Sub

function echoAndLog(sText)
'EchoAndLog Function:
' Writes string data provided by "sText" to the console and to Log file
' Requires: 
'     sText - a string containig text to write
'     oLog - a pre-existing Scripting.FileSystemObject.OpenTextFile object
	'If we are in cscript, then echo output to the command line:
	If LCase( Right( WScript.FullName, 12 ) ) = "cscript.exe" Then
		wscript.echo sText
	end if
	'Write output to log either way:
	oLog.writeLine sText
end function

function fKillProcs(aKills)
' Requires:
'     aKills - an array of strings, with each entry being the name of a running process.   
	Dim cProcs
	Dim sProc, sQuery
	Dim oWMISvc, oProc

	Set oWMISvc = GetObject("winmgmts:{impersonationLevel=impersonate, (Debug)}\.rootcimv2")
	sQuery = "Select Name from Win32_Process Where " 'Root query, will be expanded.	
	'Complete the query string using process names in "aKill"
	for each sProc in aKills
		sQuery = sQuery & "Name = '" & sProc & "' OR "
	next
	'Remove the trailing " OR" from the query string
	sQuery = Left(sQuery,Len(sQuery)-3)

	'Create a collection of processes named in the constructed WQL query
	Set cProcs = oWMISvc.ExecQuery(sQuery, "WQL", 48)
	echoAndLog vbCrLf & "----------------------------------"
	echoAndLog "Checking for processes to terminate..."
	'Set this to look for errors that aren't fatal when killing processes.
	On Error Resume Next
	'Cycle through found problematic processes and kill them.
	For Each oProc in cProcs
	   echoAndLog "Found process " & oProc.Name & "."
	   oProc.Terminate()
	   Select Case Err.Number
		   Case 0
			   echoAndLog "Killed process " & oProc.Name & "."
			   Err.Clear
		   Case -2147217406
			   echoAndLog "Process " & oProc.Name & " already closed."
			   Err.Clear
		   Case Else
			   echoAndLog "Could not kill process " & oProc.Name & "! Aborting Script!"
			   echoAndLog "Error Number: " & Err.Number
			   echoAndLog "Error Description: " & Err.Description
			   echoAndLog "Finished process termination function with error."
			   echoAndLog "----------------------------------"
			   echoAndLog vbCrLf & "Kill and Exec script finished."
			   echoAndLog "**********************************" & vbCrLf
			   WScript.Quit(101)
	   End Select
	Next
	'Resume normal error handling.
	On Error Goto 0
	echoAndLog "Finished process termination function."
	echoAndLog "----------------------------------"
end function

function fGetHlpMsg(sReturn)
' Gets known help message content for the return code provided in "sReturn".
' Requires:
'     Existing WScript.Shell object named "oShell"
	Dim sCmd, sLine, sOut
	Dim oExec
	sCmd = "net.exe helpmsg " & sReturn
	echoAndLog "Help Text for Return Code:"
	set oExec = oShell.Exec(sCmd)
	Do While oExec.StdOut.AtEndOfStream  True
		sLine = oExec.StdOut.ReadLine
		sOut = sOut & sLine
	Loop
	fGetHlpMsg = sOut
end function
'
' End Define Functions
'''''''''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Parse Arguments
If WScript.Arguments.Named.Count > 0 Then
	Set cScrArgs = WScript.Arguments.Named
	For Each sScrArg in cScrArgs
		Select Case LCase(sScrArg)
			Case "nokill"
				bNoKill = true
			Case "noexec"
				bNoExec = true
			Case "kill"
				aKills = Split(cScrArgs.Item(sScrArg), ";", -1, 1)
			Case "exe"
				sExe = cScrArgs.Item(sScrArg)
			Case "args"
				aExeArgs = Split(cScrArgs.Item(sScrArg), ";", -1 ,1)
			Case Else
				bBadArg = True
				sBadArg = sScrArg
		End Select
	Next
	If (IsNull(sExe) or IsEmpty(sExe)) Then
		bNoExeArg = True
	ElseIf (IsNull(aKills) or IsEmpty(aKills)) Then
		bNoKillArg = True
	End If
ElseIf WScript.Arguments.Named.Count = 0 Then 'Detect if required args are not defined.
	bNoArgs = True
End If 
' End Argument Parsing
'''''''''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Initialize Logging
sTemp = oShell.ExpandEnvironmentStrings("%TEMP%")
sLog = "killAndExec-" & sExe & ".log"
Set oLog = oFS.OpenTextFile(sTemp & "" & sLog, 2, True)
' End Initialize Logging
'''''''''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''''''''
' Process Arguments
if bBadArg then
	echoAndLog vbCrLf & "Unknown switch or argument: " & sBadArg & "."
	echoAndLog "**********************************" & vbCrLf
	subHelp
	WScript.Quit(100)
elseif bNoArgs then
	echoAndLog vbCrLf & "Required arguments were not specified."
	echoAndLog "**********************************" & vbCrLf
	subHelp
	WScript.Quit(100)
elseif bNoExeArg then
	echoAndLog "Required argument 'exe' was not provided."
	echoAndLog "**********************************" & vbCrLf
	subHelp
	wscript.quit(100)
elseif bNoKillArg then
	echoAndLog "Required argument 'kill' was not provided."
	echoAndLog "**********************************" & vbCrLf
	subHelp
	wscript.quit(100)
end if
' Log processes to kill:
for each sKill in aKills
	echoAndLog "Process to kill: " & sKill
next
' Log executable arguments:
echoAndLog "Executable to run: " & sExe
if not (IsNull(aExeArgs) or IsEmpty(aExeArgs)) then
	for each sExeArg in aExeArgs
		echoAndLog "Executable argument: " & sExeArg
	next
else 
	echoAndLog "Executable has no provided arguments."	
end if
' End Process Arguments
'''''''''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''''''''
'Begin Main
'
'Build full command string:
if inStr(sExe," ") then 'Spaces in the exe file
	sExe = quote & sExe & quote 'Add quotations around the executable.
end if
if not (IsNull(aExeArgs) or IsEmpty(aExeArgs)) then
	sCmd = sExe & " " 
	for each sExeArg in aExeArgs
		if inStr(sExeArg," ") then
			sExeArg = quote & sExeArg & quote 'Add quotations around the argument.
		end if
		sCmd = sCmd & sExeArg & " "
	next
else
	sCmd = sExe
end if
echoAndLog "Command to execute:"
echoAndLog sCmd

'Kill requested processes:
if bNoKill = false then
	fKillProcs aKills
else
	echoAndLog "/noKill switch has been set.  Processes will not be terminated."
end if
'Run the requested command:
echoAndLog vbCrLf & "----------------------------------"
if bNoExec = false then
	echoAndLog "Running the command..."
	on error resume next 'Disable exit on error to allow capture of oShell.Run execution problems.
	iReturn = oShell.Run(sCmd,10,True)
	if err.number  0 then 'Gather error data if oShell.Run failed.
	    echoAndLog "Error: " & Err.Number
		echoAndLog "Error (Hex): " & Hex(Err.Number)
		echoAndLog "Source: " &  Err.Source
		echoAndLog "Description: " &  Err.Description
		iReturn = Err.Number
		Err.Clear
		wscript.quit(iReturn)
	end if
	on error goto 0
	echoAndLog "Return code from the command: " & iReturn
	if iReturn  0 then 'If the command returned a non-zero code, then get help for the code:
		fGetHlpMsg iReturn
	end if 
else
	echoAndLog "/noExec switch has been set.  Executable will not run."
end if
echoAndLog "----------------------------------"

oLog.Close
wscript.quit(iReturn)
'
' End Main
'''''''''''''''''''''''''''''''''''''''''''''''''''

WiFi Profiles for Windows 8

So Windows 8 is here, to little fanfare at the University.  While I am always happy to have an updated version of Windows to work with, I see that I have yet to blog anything about it.  Perhaps that is because, unlike with the release of Windows 7, there was so little that was relatively “wrong” with the previous release.  I find myself with not much “to do” to get the enterprise ready for Windows 8.  Other reasons for the lack of hype… Windows 7 applications seem, for the most part, to “just work” on Windows 8, thus necessitating very little in the way of application compatibility planning.

Still, we have run into a few hiccups.  I spent most of the last two days updating the UVM WiFi Configuration Tool scripts and experimenting with Group Policy settings to make WPA2-protected wireless working consistently (Previously discussed here, way back in ought-eight.).  In the end, there was very little that I did to the WiFi policies that was Windows 8 specific.  The WiFi profile that we are using maintains backward compatibility with both Windows 7 and Windows Vista.

Here are the details:

  • The 802.1x settings in our WiFi profile was updated to use “user authentication” instead of “user or computer authentication”.  Under XP, this option was called “user reauthentication”.  “ReAuthentication” meant that the computer would attempt to log on as the computer account, but that if the connection was lost, it would re-authenticate as the logged on user.  Under XP, it was not possible to prevent computer authentication attempts.  However, under Win7/Win8, user authentication is just that… only user authentication is attempted, computer authentication is excluded.  We have verified this by looking at the RADIUS server logs.  Switching to “user authentication” will cut down on log errors on the RADIUS servers, and will result in fewer errors on client systems as well.
  • We have added a new trust anchor for our RADIUS server certificate in the WiFi profile.  This was necessitated by mergers and acquisitions on the CA business.  “Equifax” provided our original WPA2/PEAP certificate.  When we went to renew our certificate, we found that Equifax had been acquired by GeoTrust, and that new certificates would be issued from a GeoTrust intermediate CA.  However, this intermediate CA would be cross-signed using the Equifax root CA, so the Equifax trust anchor would still work.  The problem is that if a system has both the GeoTrustandEquifax certs present in the local trusted roots certificate store, it will validate the “radius.uvm.edu” up to the GeoTrust anchor, and will ignore the cross-signing with Equifax.  This results in WiFi connection errors.  When I add the GeoTrust cert as an additional trust anchor, the problem goes away.
  • The VBScript I use to install the WiFi profile is packaged inside a 7-Zip self extractor.  The use of this self-extractor triggers the Windows “Program Compatibility Assistant”, which in turn raises a “This program might not have installed correctly” error after the tool runs.  This problem is corrected by embedding a “manifest” file into the tool.  Typically, this is done using the “mt.exe” tool included in the Windows SDK.  Unfortunately, MT.exe corrupts self-extracting 7-Zip archives (this also is a known problem with WinRAR, and perhaps other similar tools).  Fortunately I was able to work around the problem using “Resource Tuner” from Heaventools.  I needed to add “trustInfo” and “compatibility” sections to the manifest.  My blog engine is really bad about posting XML content in a page, so I will forego posting the manifest here. You can find sample manifests pretty easily though Google.
  • When we run the packaged configuration tool, we get a warning that the application package is unsigned and may not be trustworthy.  I used “signtool.exe” from the Windows SDK to add a signature to the executable, so now it is considered somewhat more trustworthy.  Good instructions on the use of signtool.exe can be found here:
    http://www.tech-pro.net/code-signing-for-developers.html
    I am using a code signing cert that we obtained from the InCommon.org certificate service, hosted by Comodo.  It works.
  • Finally, I updated the profile installer VBScript to make reconfiguration a bit easier (subroutines were converted to functions so that variables set at the start of the script can be passed down to the function.  We then can set things like the trust anchor name, WiFi network name, and log file name at the start of the script where they are more easily edited.  Also, I removed support for Windows XP… no more Service Pack detection, Hotfix installation, or third-party profile installation utilities are needed by the script.  I was able to hack the script down to about a quarter of its original size as a result.  The new script is included below, for those who like that sort of thing…

 


Option Explicit
'On Error Resume Next
'Install UVM WPA2-Enterprise wireless profile
' Version 1.3 by J. Greg Mackinnon, University of Vermont
' Supported platforms:  Windows Vista, 7, and 8
' Requires external tools:  "CertMgr.exe" (from the Windows Platform SDK)
' Requires external files:  Root CA certificate file, 
'                           WiFi XML configuration files for Vista+ Windows OS.
'                            (obtained by running "netsh wlan export profile UVM ."
' NOTE: modify variables in the "Define variables" section to suit your environment.

'History:
' Version 1.0 - Supported UVM WiFi using WPA2, Equifax certs, Windows XP SP2+ and Vista OS
' Version 1.1 - Updated to support Windows 7
' Version 1.2 - Updated to support Windows 8.  Removed support for XP 
'             - Removed third-party "ZWlanCfg" utility and OS Hotfix installation functions (were only needed for XP support)
' Version 1.3 - Converted existing subroutines to functions to allow for easier switching of CAs and WiFi networks.
'             - Moved Global Variables to the top of the script for easier modification.
'             - Updated CA cert and WPA Profile supporting files to use "GeoTrust" instead of "Equifax".

' Create constants
Const cLogFile = "install_UVM_WiFi.log"

' Declare variables
Dim oShell, oUserEnv, oFSO, oFile, oRegExp
Dim iSPVer
Dim sTempEnv, strComputer, sOSTest, sOS, sCertName, sCertFile, sNetName, sProfileFile
Dim bReRun

' Define variables
bReRun = False
strComputer = "."
sOSTest = "Vista|Windows 7|Windows 8" 'Regular Expression for OS compatibility testing
sCertName = "GeoTrust Global CA"      'Friendly name of the trust anchor certificate
sCertFile = "GeoTrustGlobalCA.cer"    'Name of the trust anchor file
sNetName = "UVM"                      'Name of the WiFi Access Point
sProfileFile = ".Wi-Fi-UVM.xml"      'Name of the Vista+ wlan profile file.

' Instantiate global objects
Set oShell = WScript.CreateObject("WScript.Shell")
Set oFSO = CreateObject("Scripting.FileSystemObject")
sTempEnv = oShell.ExpandEnvironmentStrings("%TEMP%") & ""
Set oFile = oFSO.CreateTextFile(sTempEnv & cLogFile,True)
Set oRegExp = New RegExp
oRegExp.IgnoreCase = True
oRegExp.Global = True
oRegExp.Pattern = sOSTest

'''''''''''''''''''''''''''''''''
' Define Functions
'
Function fDetectOS(sOS, iSPVer)
'Detect OS Function - detects OS Caption string and Service Pack integer from WMI WIN32_OperatingSystem.
'Expects to varibles passed, returns the full OS Caption String, and SP Major Version intger
	'Declare variables
	Dim colItems
	Dim objWMIService, objItem
	'Instantiate local objects/collections
	Set objWMIService = GetObject("winmgmts:\" & strComputer & "rootCIMV2") 
	Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")

	For Each objItem In colItems
	  sOS = objItem.Caption
	  oFile.WriteLine "Detected Operating System: " & sOS
	  iSPVer = CInt(objItem.ServicePackMajorVersion)
	  oFile.WriteLine "Detected Service Pack Version: " & iSPVer
	  oFile.WriteLine "Service Pack Minor Version: " & objItem.ServicePackMinorVersion
	Next
	
	'Clean local objects/variables
	Set objItem = Nothing
	Set colItems = Nothing
	Set objWMIService = Nothing
End Function

Function fInstCert(sCertName,sCertFile)
' Installs cert with sCertName root CA cert into machine "root" store.
' Requires:  certmgr.exe from the Windows Platform SDK (available with VS .NET or VS 2008 installations), 
'	sCertName variable - contains the friendly name of the root CA
'	sCertFile variable - contains the name of the root CA certificate file
' Requres:  Root CA cert file
' Notes:  We use the "root" argument to certmgr.exe to install into the "Trusted Root Certificate Authorities".  
'		We also could use "ca" to install Intermediate Certificate Authorities.
'		In a previous version of this script we used "oShell.Run", but his returned unexpected results on the
'		Windows 7 platform... using .Exec now.
	
	Dim bCertPresent, bInstSuccess
	Dim oExec
	Dim sOut

	bCertPresent = false
	bInstSuccess = false
	
	set oExec = oShell.Exec("certmgr.exe -c -s -r localMachine root")

	Do Until oExec.StdOut.AtEndOfStream
		sOut = oExec.StdOut.ReadLine()
		if InStr(sOut, sCertName) Then
			'oFile.WriteLine sOut
			'WScript.Echo sOut
			bCertPresent = true
		End If
	Loop

	if bCertPresent = false then
		oFile.WriteLine "Root Certificate for """ & sCertName & """ needs to be installed.  Attempting install..."
		set oExec = oShell.Exec("certmgr.exe -add -c " & sCertFile & " -s -r localMachine root")
		Do Until oExec.StdOut.AtEndOfStream
			sOut = oExec.StdOut.ReadLine()
			if InStr(sOut, "Succeeded") Then
				'oFile.WriteLine sOut
				bInstSuccess = true
			End If
		Loop
		if bInstSuccess = true then
			oFile.WriteLine "Certificate installed successfully"
		else 
			oFile.WriteLine "Certificate failed to install... You will need to install the " _
				& "certificate manually.  See the instructions at https://www.uvm.edu/ets/wireless " _
				& ", then run this script again to compelte installation of the UVM wireless profile."
			WScript.Quit -2
		end if
	else
		oFile.WriteLine "Root Certificate for """ & sCertName & """ is already installed."
	End If
End Function

Function fImportProfile(sProfileFile,sNetName)
'Imports Vista+ Wireless Profile using NETSH command.  
'Requires: a Vista+ wifi profile file exported using NETSH, 
'	sProfileFile - string containing name of the wlan XML profile file to be imported
'	sNetName - string contining the name of the wlan profile name (WiFi Network Name)

	'On Error Resume Next
	Const cUserScope = "all"
	
	Dim iStrMatch
	Dim oExec, oStdOut
	Dim sStdOutLine
	
	oFile.WriteLine "Executing command: netsh wlan add profile filename=""" & sProfileFile & """ user=" & cUserScope & ""
	Set oExec = oShell.Exec("netsh wlan add profile filename=""" & sProfileFile & """ user=" & cUserScope & "")
	Set oStdOut = oExec.stdOut
	While Not oStdOut.AtEndOfStream
		sStdOutLine = oStdOut.ReadLine
		oFile.WriteLine(sStdOutLine)
		iStrMatch = CInt(InStr(sStdOutLine, "Profile " & sNetName & " is added on interface"))
		If iStrMatch > 0 Then
			WScript.Echo "The " & sNetName & " wireless profile was added successfully to your system"
		ElseIf iStrMatch = 0 Then
			WScript.Echo "The wireless profile failed to import.  Please see the manual profile " _
			& "configuration instructions available at http://www.uvm.edu/ets/wireless.  A " _
			& "log file named " & cLogFile & " which contains the full error message can be " _
			& "found in the " & sTempEnv & " directory."
			WScript.Quit -3
		End If
	Wend
	
	Set oStdOut = Nothing
	Set oExec = Nothing
End Function
'
' End Functions
'''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''
' Begin Main
'

fDetectOS sOS, iSPVer

If oRegExp.Test(sOS) = True Then
	fInstCert sCertName, sCertFile
	fImportProfile sProfileFile, sNetName
Else
	oFile.WriteLine "Your operating system is not supported for use with this script."
	WScript.Quit -4
End If

oFile.close

' Environment cleanup 
Set oFile = Nothing
Set oFSO = Nothing
Set oUserEnv = Nothing
Set oShell = Nothing
Set oRegExp = Nothing

'
' End Main
''''''''''''''''''''''''''''''''''