Archive for the ‘Scripting the Windows Experience’ Category

Moving User Profiles with PowerShell

Something that comes up with some frequency on Terminal Servers (or “Remote Desktop Servers”), but perhaps sometimes in VDI, is “How to I move a user profile from one drive to another”. The traditional answers include the use of the user profile management GUI, or some expensive piece of software. But what if you need to automate the job? Or if you don’t have any money for the project?

Answer? PowerShell, of course… and robocopy.

Below is a code snippet that will set existing user profiles to load from “C:\Users” to “E:\Users”:

#Collect profile reg keys for regular users ("S-1-5-21" excludes local admin, network service, and system)
$profiles = gci -LiteralPath "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" `
	| ? {$ -match "S-1-5-21-"} 

foreach ($profile in $profiles) {
	#Set the registry path in a format that can be used by the annoyingly demanding "get-itemproperty" cmdlet:
	$regPath = $(
		$($profile.pspath.tostring().split("::") | Select-Object -Last 1).Replace("HKEY_LOCAL_MACHINE","HKLM:")
	#Get the current filesystem path for the user profile, using get-ItemProperty"
	$oldPath = $(
		Get-ItemProperty -LiteralPath $regPath -name ProfileImagePath
	#Set a varialble for the new profile filesystem path:
	$newPath = $oldPath.Replace("C:\","E:\")
	#Set the new profile path using "set-itemproperty"
	Set-ItemProperty -LiteralPath $regPath -Name ProfileImagePath -Value $newPath

#Now copy the profile filesystem directories using "robocopy".

But this code will not actually move the data. For that, we need robocopy. Make sure that your users are logged off before performing this operation, otherwise “NTUSER.DAT” will not get moved, and your users will get a new TEMP profile on next login:

robocopy /e /copyall /r:0 /mt:4 /b /nfl /xj /xjd /xjf C:\users e:\Users

Finally, be sure to set the default location for new profiles and the “Public” directory to your new drive as well. For that, run “Regedit”, then go to:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
and set new paths for the registry strings “ProfilesDirectory” and “Public”. Moving the default user profile is optional.

Oh yeah… you might want to purge the old Recycle Bin cruft for your moved users as well:

rmdir /s /q C:\$Recycle.Bin

SharePoint 2010 – Email Alerts to Site Administrators

We are in the final stages of preparation for the long-overdue upgrade to SharePoint 2010.  I have set up a preview site with a copy of the production SharePoint content database, and I want to notify all site owners that they should check out their sites for major problems.  How to do?  PowerShell?  Absolutely!

Set-PSDebug -Strict
Add-PSSnapin -Name microsoft.SharePoint.PowerShell

[string] $waUrl = ""
[string] $SmtpServer = ""
[string] $From = ""

$allAdmins = @()

[string] $subjTemplate = 'Pending Upgrade for your site -siteURL-'
[string] $bodyTemplate = @"
Message Body Goes Here.
Use the string -siteURL- in the body where you want the user's site address to appear.

$wa = Get-SPWebApplication -Identity $waUrl

foreach ($site in $wa.sites) {
	#Write-Host "Working with site: " + $site.url
	$siteAdmins = @()
	$siteAdmins = $site.RootWeb.SiteAdministrators
	ForEach ($admin in $siteAdmins) {
		#Write-Host "Adding Admin: " + $admin.UserLogin
		[string]$a = $($admin.UserLogin).Replace("CAMPUS\","")
		[string]$a = $a.replace(".adm","")
		[string]$a = $a.replace("-admin","")
		[string]$a = $a.replace("admin-","")
		if ($a -notmatch "sa_|\\system") { $allAdmins += , @($a; [string]$site.Url) }

$allAdmins = $allAdmins | Sort-Object -Unique
#$allAdmins = $allAdmins | ? {$_[0] -match "jgm"} | Select-Object -Last 4

foreach ($admin in $allAdmins) {
	[string] $to = $admin[0] + ""
	[string] $siteUrl = $admin[1]
	[string] $subj = $subjTemplate.Replace("-siteURL-",$siteUrl)
	[string] $body = $bodyTemplate.Replace("-siteURL-",$siteUrl)
	Send-MailMessage -To $to -From $From -SmtpServer $SmtpServer -Subject $subj -BodyAsHtml $body

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
		end select
	if (IsNull(sInstall) or IsEmpty(sInstall)) then
		echoAndLog "Required argument 'setup' was not provided."
		echoAndLog "**********************************" & vbCrLf
	elseif (IsNull(sBaseVer) or IsEmpty(sBaseVer)) then
		echoAndLog "Required argument 'basever' was not provided."
		echoAndLog "**********************************" & vbCrLf
	elseif (IsNull(sPatch) or IsEmpty(sPatch)) then 
		bDoPatch = False
		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
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 & "\Adobe\Reader 10.0\Reader\AcroRd32.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..."
	'Install the base product.
	echoAndLog "Installing base product with command: " & sInstall
	set oExec = oShell.Exec(sInstall)
	Do While Not oExec.Status  1
	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
	sOut = oExec.StdOut.ReadAll()
	echoAndLog "Return code from patch installer: " & oExec.ExitCode
	echoAndLog "Standard output: " & sOut
	iExit = cLng(oExec.ExitCode) + iExit
	echoAndLog "Patch installation was not requested.  Exiting."
end if

' End Main

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.
' 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)}\\.\root\cimv2")
	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 "
	'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 & "."
	   Select Case Err.Number
		   Case 0
			   echoAndLog "Killed process " & oProc.Name & "."
		   Case -2147217406
			   echoAndLog "Process " & oProc.Name & " already closed."
		   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
	   End Select
	'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
	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
	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
elseif bNoArgs then
	echoAndLog vbCrLf & "Required arguments were not specified."
	echoAndLog "**********************************" & vbCrLf
elseif bNoExeArg then
	echoAndLog "Required argument 'exe' was not provided."
	echoAndLog "**********************************" & vbCrLf
elseif bNoKillArg then
	echoAndLog "Required argument 'kill' was not provided."
	echoAndLog "**********************************" & vbCrLf
end if
' Log processes to kill:
for each sKill in aKills
	echoAndLog "Process to kill: " & sKill
' 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
	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 & " "
	sCmd = sExe
end if
echoAndLog "Command to execute:"
echoAndLog sCmd

'Kill requested processes:
if bNoKill = false then
	fKillProcs aKills
	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
	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 
	echoAndLog "/noExec switch has been set.  Executable will not run."
end if
echoAndLog "----------------------------------"

' 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 “” 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:
    I am using a code signing cert that we obtained from the 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.

' 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 & "\root\CIMV2") 
	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
	'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

	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
		if bInstSuccess = true then
			oFile.WriteLine "Certificate installed successfully"
			oFile.WriteLine "Certificate failed to install... You will need to install the " _
				& "certificate manually.  See the instructions at " _
				& ", then run this script again to compelte installation of the UVM wireless profile."
			WScript.Quit -2
		end if
		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
		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  A " _
			& "log file named " & cLogFile & " which contains the full error message can be " _
			& "found in the " & sTempEnv & " directory."
			WScript.Quit -3
		End If
	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
	oFile.WriteLine "Your operating system is not supported for use with this script."
	WScript.Quit -4
End If


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

' End Main

Thunderbird 13 – The cloud arrives

Mozilla Thunderbird 13 arrived this week.  Guess what?  Our customized build process broke again.  Now, when you start TB for the first time, you get greeted with the option to create a new email account with one of Thunderbird’s “partners” (in other words, email providers who paid for the honor of being put in the “welcome to Thunderbird” start dialog).

With the assistance of the awesome Ben Coddington (who does not keep a blog, but should so that you can bask in his awesomeness), I was able to track down the place that the new-new account dialog is called, and kill it by switching a preference in the “thunderbird-all.js” file.

The preference is a Boolean named “mail.provider.enabled”, set in the thunderbird-all.js file, as documented here:
and referenced here:
and here:

I updated our Thunderbird build script to set this preference to “false”:

Echo modifying default "All Thunderbird" preferences...
..\..\..\bin\sed.exe --binary "s/pref(\"mail.provider.enabled\", true);/pref(\"mail.provider.enabled\", false);/"  .\defaults\pref\all-thunderbird_new.js
if errorlevel 1 goto err
MOVE /Y .\defaults\pref\all-thunderbird_new.js .\defaults\pref\all-thunderbird.js

The whole ugly build script is provided below:

REM Thunderbird customized build script for UVM.
REM Updated June 2012 for Thunderbird 13 support.
REM 	- 7z.exe, 7zr.exe and sed.exe in parallel "..\bin" directory
REM     - Unmodified Thunderbird installer in .\source directory
REM		- all required config files in .\config directory
REM     	(including 7z control file, ISP Hook RDF file, and modified prefs.js)
REM		- local JDK install with "jar.exe".  Path to jar.exe will need to be updated in the jdk environment variable
REM OUTPUT: Fully modified Thunderbird installer in .\Installer directory.
REM @echo on

set jdk="c:\Program Files (x86)\Java\jdk1.6.0_27\bin"

Echo Cleaning up old builds...
del .\Installer\*.exe
rmdir /s /q .\build
set /P tbver=Enter Thunderbird version number to build (i.e. "6.0.2"):

Echo Extracting setup files from OEM Installer...
mkdir .\build\temp
..\bin\7zr x .\source\*.exe -o.\build

Echo Extracting omni.ja contents...
mkdir .\build\temp
cd .\build\temp
%jdk%\jar.exe xf ..\core\omni.ja
if errorlevel 1 goto err

Echo modifying messenger functions...
..\..\..\bin\sed.exe --binary "s/NewMailAccount(msgWindow, okCallback);/MsgAccountWizard(okCallback);/"  .\chrome\messenger\content\messenger\msgMail3PaneWindow_new.js
if errorlevel 1 goto err
MOVE /Y .\chrome\messenger\content\messenger\msgMail3PaneWindow_new.js .\chrome\messenger\content\messenger\msgMail3PaneWindow.js

Echo modifying default "All Thunderbird" preferences...
..\..\..\bin\sed.exe --binary "s/pref(\"mail.provider.enabled\", true);/pref(\"mail.provider.enabled\", false);/"  .\defaults\pref\all-thunderbird_new.js
if errorlevel 1 goto err
MOVE /Y .\defaults\pref\all-thunderbird_new.js .\defaults\pref\all-thunderbird.js

Echo modifying default mailnews preferences...
..\..\..\bin\sed.exe --binary "s/try_ssl\", 0)/try_ssl\", 2)/"  .\defaults\pref\mailnews_new.js
if errorlevel 1 goto err
MOVE /Y .\defaults\pref\mailnews_new.js .\defaults\pref\mailnews.js

Echo moving UVM modified prefs.js into place (note that this file is not actually used by Thunderbird!)
copy /Y ..\..\config\prefs.js .\defaults\profile\prefs.js

Echo Repacking omni.ja...
del /f /q ..\core\omni.ja
%jdk%\jar.exe cf ..\core\omni.ja *

Echo Copying UVM Custom ISP file to source...
cd ..\..\
mkdir .\build\core\isp\en-US
copy /Y .\config\UVMMail.rdf .\build\core\isp\en-US\UVMMail.rdf
if errorlevel 1 goto err
Echo Copying UVM default prefs.js to core directory (tbird no longer has a prefs.js by default, but it will be used if present)...
mkdir .\build\core\defaults\profile
copy /Y .\config\prefs.js .\build\core\defaults\profile\prefs.js
if errorlevel 1 goto err

Echo Deleting temporary files that should not be present in the installer...
rmdir /s /q .\build\temp

Echo Repackaging Thunderbird installer...
..\bin\7zr a .\Installer\UVM_Thunderbird_setup_%tbver%.7z .\build\*
copy /b ..\bin\7zS.sfx + .\config\config.txt + .\Installer\UVM_Thunderbird_setup_%tbver%.7z .\Installer\UVM_Thunderbird_setup_%tbver%.exe

Echo Cleaning up installation source...
del /s /f /q .\build\*.*
rmdir /s /q .\build\core
rmdir /s /q .\build
del /f /q .\Installer\UVM_Thunderbird_setup_%tbver%.7z
goto end

echo There was an error running a command.


The Mysterious Case of the Un-Deletable MBR (Or, More Reasons to Hate PGP)

Shortly after releasing MDT 2012 on the general public I got a call from a colleague who told me that his LiteTouch deployment was failing.  He was able to boot to LiteTouch media, go though the configuration wizard, and initiate setup.  LiteTouch would partition the drive, Windows Setup would start, the image would get written to the computer, and then the system would reboot… so far so good. What happened next was unexpected.  The computer booted to the PGP BootGuard screen.

Turns out we were dealing with a system that had been encrypted using PGP Whole Disk Encryption. However, we have a lot of those, and deployment has not failed on them before.  In the past, LiteTouch dutifully has erased the Master Boot Record (MBR) and all existing partition tables on the system, effectively wiping PGP BootGuard from the machine before running Windows Setup.

So what changed?  Is this a bug in MDT 2012?  Something new in PGP Desktop version 10.2.0 MP4?  Or a configuration problem in our LiteTouch environment.

Let’s omit the details of ~6 hours of troubleshooting… it was a change in the WinPE LiteTouch environment, and PGP.  It appears, though investigation, that the PGP filter drivers attempt to block access to the MBR of the hard drive.  Since I had injected PGP drivers into the LiteTouch 32-bit boot media, I had, effectively created a situation where DiskPart.exe would be unable to remove PGP BootGuard from the system.  The really irritating part is that the PGP drivers do not pass any indication to the Windows utilities that there has been an error writing to the MBR.  DiskPart.exe, BootSect.exe, and the DaRT Disk Commander all can be used to repair MBRs.  But when used in a PGP-enabled environment they all report success in manipulating the disk MBR, but all of them fail to make any real change to the true MBR.  How do you usually erase a drive?  For me, I would run “diskpart.exe, select disk 0, clean”.  With PGP drivers in place, you could run this series of commands, think that you had erased the drive, but still end up with PGP BootGuard in your MBR.  It really is maddening.

Symantec/PGP claim that you can remove the MBR data by “deinstrumenting” the disk using the “pgpwde.exe” command.  The problem with this is, pgpwde will not let you deinstrument an encrypted drive.  So, you would have to decrypt the drive first, then deinstrument.  I am not wasting time on that.  Worse yet, if your drive was partially encrypted when you erased the data partition, PGPWDE still reports the drive status as “partially encrypted”, and refuses to perform any actions on the drive (such as “deinstrument”) until the current encryption (on the nonexistent drive) completes.  AARGH!

Fortunately, I was able to find a low-level disk manipulation utility that actually works in 32-bit PGP-enabled WinPE environments.  PlDD.exe:

There are other “DD” equivalents for Windows.  Most of them either fail to work against PGP (GnuWin32 DD.exe and the Crysocome DD), or will not function under WinPE (FAU DD).  PlDD is pretty old, and it does not work under 64-bit Windows.  But, we don’t need 64-bit support (PGP does not provide 64-bit drivers for WinPE!), it works perfectly in 32-bit Windows.  Thus, this is the perfect tool for the time being.

Getting the right command syntax to pldd.exe was a bit challenging as the tool itself has scarce documentation.  I wish I could credit all of the resources that I used to put this dense command together, but I have since lost the browser tabs.  The following is the pldd.exe command, suitable for plugging into an MDT task sequence as a custom command:

cmd.exe /c “%SCRIPTROOT%\Pldd.exe if of=\\.\PhysicalDrive0 bs=512 count=1″

Argument breakdown:

  • if = In File.  In this version of DD, if provided with parameters, will use a string of zeros as input.
  • of = Out file.  In this case, we are using the Windows device path “\\.\PhysicalDrive0″, which is fixed disk zero.  I think this device path is referenced in the gnuwin32 dd docs.
  • bs = Block size.  We are choosing to write in 512 byte blocks.
  • count = The number of blocks to write.  We are going to write one 512 byte block to the “out file”.

To summarize, we use pldd to write 512 bytes of zeros to the start of physical drive zero.  This action wipes out the MBR and the disk signature of the drive (sorry, I lost my reference for this factoid, too).  Zeroing 512 bytes of disk is rather faster than zeroing the entire drive, which is the only other option I have seen referenced in the tubes for fixing this issue.

Share and Enjoy.

MDT 2012 – Taking LiteTouch Offline

I decided to give some of my user base something that they have been asking for for a long time… the ability to run MDT/LiteTouch deployments entirely from removable storage media. I had avoided doing this in the past as we made significant use of the MDT database in selecting hardware-specific support applications (such as Dell QuickSet).  However, with MDT 2012 (and the general deprecation of hardware-specific support software under Windows 7), I have decided to abandon the MDT database.  This makes generation of offline MDT media much more feasible.

“I should be able to get this done in a few hours!”, I thought.  Ha!  Four days later…

Gotchas in adding LiteTouch Offline media to a previously online-only environment:

Expiring stale media:

One of the leading arguments we make to persuade users to adopt the use of LiteTouch is that “we keep it up to date for you”.  What about offline media?  How to we ensure that that stays current?  One of the Brad Tucker, Deployment Guy, has a solution for that:

The problem there is that his script was developed for the SCCM ZTI scenatio, not LiteTouch.  However, with a little work I was able to adapt his script for use in LiteTouch.  The script body is available below.  To run it, I needed to modify the “winpeshl.ini” file in %ProgramFiles%\Microsoft Deployment Toolkit\Templates as follows:


The script referenced above (ZUVMExpiredMediaCheck.vbs) needs to be defined in the “Extra Directory to Include” field in the WinPE section of the Media set in the Deployment Workbench.  You need to include the “\Deploy\Scripts” folder structure in the Extras directory, too.

WinRE installation problems:

Since deploying MDT 2012, I finally worked though the problem of including both WinRE and MS DaRT tools into the LiteTouch boot media, and in the WinRE environment installed with the operating system.  However, with offline media the inclusion we would not want to copy the LiteTouch WinPE instance to disk.  Two reasons.  Firstly, the OS Deployment option simply would not work (Offline media would not be available), and secondly, we just included a script to disable the media.  To solve this problem, I needed to set the “PrepareWinRE” Property in the CustomSettings.ini file for the media set to “NO”.

MS DaRT Integration Problem:

When testing LiteTouch from a fully offline machine, I started to get a “network connection not available” error pop up at seemingly random places after starting up the boot media.  Eventually I realized that the error was coming from the DaRT Remote Connection tool that starts up with WinPE.  While this error does not cause any problems with actual deployment, I don’t want it causing end-user panic, so I decided to see if I could disable the feature.  According to documentation, I need to generate a “DartConfig.DAT” file using the DaRT configuration tool.  DartConfig.DAT is a binary configuration file (not plain text).  It’s options are not documented anywhere, so you really do have to run the GUI tool to generate a new DAT.  You then are supposed to drop the DAT file into “%ProgramFiles%\Microsoft Deployment Toolkit\Templates”, and update your boot media.  A few problems with this:

  1. If you want different configuration files installed into your WinPE instances, you will either to switch out the DartConfig.dat in the Templates directory each time you update boot media, or run the updates from a different MDT instance, or edit the LiteTouch boot WIM files each time you update the boot media.  There is no way to specify different DartConfig.dat files per deployment share or media set.
  2. The Deployment Workbench does not consistently insert the DartConfig.dat file into the LiteTouch boot media.  If you update your DartConfig.dat in the Templates directory, then update your boot media, there is no guarantee that your DartConfig.dat will get updated.  The only sure-fire way to get a new DartConfig in your deployment share seems to be to force regeneration of the boot media (i.e. you need to throw out your existing boot WIM files, not update them).  The situation is worse with offline media sets.  Rather the workbench will copy any existing boot WIMs from the root deployment share to serve as a baseline image when generating offline boot images.  Thus, to update DartConfig.dat in a media set, you need to delete both the root share boot WIMs, and the offline boot WIMs prior to updating media.
  3. You might think that you could work around that whole one-template-per-workbench problem by including a per-media-set DartConfig.dat in the “Extras” folder that you can optionally include in each media set or deployment share.  After all, the media update procedure appears to add the extras after the templates.  But if you did think this, you would be wrong.  The update apparently will not overwrite existing files within the source WIM.
  4. You might, out of sheer desperation, decided to remove DaRT from the offline boot media  by deselecting the component from the WinPE properties of the media set.  This also will fail.  The workbench will report that “DaRT cannot be removed from the media.  Use the -Force option to regenerate the media.”  Presumably the error is suggesting that you should add “-force” to the Update-MDTMedia PowerShell Cmdlet that is used to update the media set.  Sadly, “-Force” is not a valid flag for this cmdlet.

Ultimately, I just used imagex to mount the LiteTouch Offline boot media, and switched out the DartConfig.dat file using a simple “copy” command.  Now I just need to remember to do that every time.

UserExit Script – Required Modifications:

Back in 2008 I added a UserExit script to LiteTouch to generate a semi-unique computer name by taking the last eight characters of the computer’s MAC address, then appending a hyphen and a date string.  It turns out that the routine in MDT that captures the MAC address (presumably ZTIGather.vbs) will not succeed unless the computer has a functional Ethernet connection.  Grrr… When testing LiteTouch offline, we were getting computer names like “Address%-1214″.  Percent characters are not valid in computer names  so, I needed to update our UserExit to use other semi-unique system attributes such as “Serial Number” to “Asset Tag” if the MAC is not available.  I also added a fallback string of “UVMLT” if none of those variables are found.  The new script is available below, along with a sample call to the script from CustomSettings.ini.

' // ****************************************************************************
' // File:      ZUVMExpiredMediaCheck.vbs
' // Version:   1.0
' // Purpose:   Check to see if stand-alone media is expired
' // Actions:   Shuts down WinPE if media is older than iExpAge variable months
' //            Otherwise, script exits with Return 0.
' // Usage:     cscript/wscript ZUVMExpiredMediaCheck.vbs
' //            (to be added to winpeshl.ini, before bddrun.exe)
' // ****************************************************************************
Option Explicit

' // Declare Variables:
Dim cFiles
Dim dtCreationDate, dtEndDate, dtXMonthsAgo
Dim iExpAge
Dim oDiskDrive, oDrives, oExec, oFile, oFSO, oShell, oWMIService
Dim sCommand, sComputer, sExpText, sSysRoot, sUSBPath

' // Initialize Variables:
' Media Expiration Age, in months:
iExpAge = 4

' // -----------------------------------------------------------------------------------------
' // Function: Converts the WMI date query response to a simple date format.  (e.g. 09/21/2010)
Function WMIDateStringToDate(dtmInstallDate)
	WMIDateStringToDate = CDate(Mid(dtmInstallDate, 5, 2) & "/" & Mid(dtmInstallDate, 7, 2) _
	& "/" & Left(dtmInstallDate, 4) & " " & Mid(dtmInstallDate, 9, 2) & ":" _
	& Mid(dtmInstallDate, 11, 2) & ":" & Mid(dtmInstallDate, 13, 2))
End Function
' // -----------------------------------------------------------------------------------------

' // ---------------------------------------------------------------------------------
' // Find the environment variable %SYSTEMROOT% for location of LiteTouch Executables.
Set oShell = CreateObject("WScript.Shell")
sSysRoot = oShell.ExpandEnvironmentStrings("%SYSTEMROOT%")
' // ---------------------------------------------------------------------------------

' // --------------------------------
' // Find driver letter for USB Media
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oDrives = oFSO.Drives
For Each oDiskDrive In oDrives
	If oDiskDrive.DriveType = "1" Then
		sUSBPath = oDiskDrive.Path
	End If
' // --------------------------------

' // -------------------------------------------------------------------------
' // Media Check - Check for Applications.xml presence and age.
sComputer = "."
Set oWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & sComputer & "\root\cimv2")
' Query WMI for creation date of the Applications.xml file on the USB Drive:
'    NOTE: Do not add the wbemFlagForwardOnly (Decimal 32) flag to this query.  While the query would run faster
' with the flag, we also will not be able test for empty queries.
Set cFiles = oWMIService.ExecQuery("Select * From CIM_DataFile Where Name = '" & sUSBPath & "\\Deploy\\Control\\Applications.xml'")
' // -------------------------------------------------------------------------

' // ---------------------------------------------------------------------------------
' // If Applications.xml file is not present, this is not offline media.  Exit script.
if cFiles.Count = 0 then
end if
' // ---------------------------------------------------------------------------------

' // ---------------------------------------------------------------------------------------------
' // If the Applications.xml file creation date is more than "iExpAge" months ago, shutdown WinPE.
For Each oFile in cFiles
	dtCreationDate = WMIDateStringToDate(oFile.CreationDate)
	dtEndDate = DateAdd("m", iExpAge, dtCreationDate)
	' Set the date iExpAge months ago from today
	dtXMonthsAgo = DateAdd("m", -iExpAge, Now)
	If dtCreationDate < dtXMonthsAgo then
		' Expiration Text, to be displayed to the user if older than iExpAge months:
		sExpText = "This LiteTouch Offline Media expired on: " & dtEndDate & chr(13) _
			& "Refresh your media using the README file located here:" & chr(13) _
			& "\\\software\Windows_Deployment_Services"
		MsgBox sExpText,vbMsgBoxSetForeground,"Expired Media"
		'Shutdown WinPE immediately:
		sCommand = sSysRoot & "\system32\wpeutil.exe shutdown"
		set oExec = oShell.Exec(sCommand)
		' If the media is fresh, run LiteTouch Offline.
	End If
' // ---------------------------------------------------------------------------------------------

' // ZUVMUserExit.vbs
' // Custom Function library for use with the Microsoft Deployment Toolkit
' // Currently includes "GenUniComp" - a function for generating unique computer names

' code adapted from source content:

Function UserExit(sType, sWhen, sDetail, bSkip)
	UserExit = Successfs
End Function

Function GenSimDate(sSimDate)
	'Generates a simple date string in the format of YYMMDD
	Dim dNow, sYear, sMonth, sDay
	dNow = Date()
	sYear = Right(cStr(Year(dNow)), 2)
	sMonth = cStr(Month(dNow))
	sDay = cStr(Day(dNow))
	GenSimDate = sYear + sMonth + sDay
End Function

Function CleanMac(sMac)
	'Strips colon (:) characters from the variable passed to this function.  The passed variable is presumed to be a Mac address.
	Dim oRegExp
	Set oRegExp = new RegExp
	oRegExp.IgnoreCase = true
	oRegExp.Global = true
	oRegExp.Pattern = ":"
	CleanMac = oRegExp.Replace(sMac, "")
End Function

Function GenUniComp(sMac,sSerial,sATag)
	'Generates a hopefully unique computer name by:
	'   Selecting from available MacAddress, SerialNumber, or Asset Tag then
	'   triming the right eight digits from the value and appending a hyphen with the current date.
	Dim sSimDate, sUniVal
	oLogging.CreateEntry "ZUVMUserExit: sMac value in UserExit script is: " & sMac,LogTypeInfo
	oLogging.CreateEntry "ZUVMUserExit: sSerial value in UserExit script is: " & sSerial,LogTypeInfo
	oLogging.CreateEntry "ZUVMUserExit: sATag value in UserExit script is: " & sATag,LogTypeInfo
	if InStr(sMac,"%Mac") = 0 then
		oLogging.CreateEntry "ZUVMUserExit: Using Mac Address to generate computer name",LogTypeInfo
		sMac = CleanMac(sMac)
		oLogging.CreateEntry "ZUVMUserExit: Cleaned sMac values now is: " & sMac,LogTypeInfo
		sUniVal = sMac
	elseif InStr(sSerial,"%Serial") = 0 then
		oLogging.CreateEntry "ZUVMUserExit: Using Serial Number to generate computer name.",LogTypeInfo
		sUniVal = sSerial
	elseif InStr(sATTag,"%Asset") = 0 then
		oLogging.CreateEntry "ZUVMUserExit: Using Asset Tag to generate computer name.",LogTypeInfo
		sUniVal = sATag
		oLogging.CreateEntry "ZUVMUserExit: Using Fallback Computer Name",LogTypeInfo
		sUniVal = "UVMLT"
	end if
	oLogging.CreateEntry "ZUVMUserExit: sUniVal now set to: " & sUniVal,LogTypeInfo
	sSimDate = GenSimDate(sSimDate)
	GenUniComp = Right(sUniVal, 8) + "-" + sSimDate
	oLogging.CreateEntry "ZUVMUserExit: Unique Computer Name will be: " & GenUniComp,LogTypeInfo
End Function

Calling the GenUniComp function from CustomSettings.ini:


Driver installation with SCCM Software Distribution

Here we are, working with SCCM again.  Making difficult things possible, and simple things difficult.  Today we wish to distribute a SmartCard driver to all of our managed servers, so that we can require Smart Card for certain classes of logins.  the newer “CNG” Smart Card minidrivers are all simple “.inf” driver packages that you can right-click install.  This ought to be easy, thought the sys admin.  Wrong!

Installation of inf drivers is not a well documented command line procedure (unlike the rather more complicated “.msi” package, which at least is easy to script).

My thanks goes out to the following bloggers and forum users for their assistance with this case:

The script that I cobbled together to install the Athena “ASECard” minidriver is displayed below.  Note that this should work for pretty much any minidriver, as long as it has a “DefaultInstall” section in the inf file.  I just unpack the amd64 and x86 driver cab files into their respective directories, put the batch script one directory above these, and make an SCCM software package of the whole thing.  The installation command line is simply the batch file name.

@echo off
REM Installs the drivers specified in the "DefaultInstall" section
REM of the aseMD.inf that is appropriate for the current (x86 or amd64) platform.
REM Install is silent (4 flag), with no reboot (N flag).
REM The INF is specified to be in the x86 or amd64 subdirectory
REM of the script directory (%~dp0).

echo Detecting platform...
IF EXIST "%programfiles(x86)%" (GOTO :amd64) ELSE (GOTO :i386)

echo Installing 32-bit driver...
cd x86
%windir%\system32\rundll32.exe advpack.dll,LaunchINFSectionEx "%~dp0x86\aseMD.inf",DefaultInstall,,4,N
goto :EOF

REM The command will run in 64-bit mode (%windir%\sysnative\),
REM when called from a 32-bit CMD.exe (as will be the case with SCCM).
echo Installing 64-bit driver...
cd amd64
%windir%\sysnative\rundll32.exe advpack.dll,LaunchINFSectionEx "%~dp0amd64\aseMD.inf",DefaultInstall,,4,N
goto :EOF
REM End of file

Windows Backup Performance Testing with PowerShell

While developing our new Windows file services infrastructure, we wanted to test our pre-production platform to see if there are any file server-side bottlenecks that will cause unacceptable delays in backup processing. Here are UVM we still are using EMC Networker for Enterprise backup (no comments on our satisfaction with EMC will be provided at this time). EMC provides a tool “uasm.exe” that is used at the core of the “save.exe” and “recover.exe” commands on the backup client. If we use “uasm.exe” to backup all of the file server data to “null”, it is possible that we will be able to detect disk, HBA, and other local I/O bottlenecks before they bite us in production.

Since Networker will break up our file server into multiple “save sets”, and run a user-definable number of save set backup processes in parallel, it also is important for us to determine the required number of parallel backup processes required to complete backup in a timely fashion. Thus, we want to run several parallel “uasm.exe” processes in our tests.

PowerShell, with the assistance of “cmd.exe”, and some finesses, can get this job done. Hurdles I ran into while scripting this test follow:

  1. During development, PowerShell consumed huge amounts of CPU while redirecting uasm.exe output to the PowerShell $null object. Interestingly, previous tests using uasm.exe with cmd.exe did not show this problem. To fix this, each uasm job is spawned from a one-line cmd.exe “bat” script, which is included below.
  2. Remember that PowerShell uses the null object “$null”, but that cmd.exe uses the handle “nul” (with one “L”). If you redirect to “null”, you will soon fill up your disk with a file named “null”.
  3. When wanted to examine running jobs, it was difficult to determine which directory a jobs was working on. This was because I initially created a scriptblock object and passed parameters to it when starting a job. For example:
    [scriptblock] $sb = {
    $uasmBlock = {
    	param ([string]$sPath)
    	[string[]] $argList = '/c','c:\local\scripts\uasm_cmd.bat',$sPath
    	& cmd.exe $argList
    $jobs += start-job -Name $myJob -ScriptBlock $sb -ArgumentList $dir1

    However, when inspecting the job object’s “command” property, we see “$sPath” in the output. We want the variable expanded. How to do this? Create the scriptblock object in-line when starting the job:

    [string] $cmd = '& cmd.exe "/c","c:\local\scripts\uasm_cmd.bat",' + $dir
    $jobs += Start-Job -Name $jobName `
    	-ScriptBlock ([scriptblock]::create($cmd))

    This makes for more compact code, too.

  4. To check on jobs that have completed, I create an array named “$djs” (Done Jobs), populated by piping the $jobs array and filtering for “completed” jobs. I inspect $djs to see if jobs are present. In my first pass, I used the check:
    if ($djs.count -gt 0)

    Meaning, continue if there is anything in the array $djs. However, this check did not work well because output from the $jobs object would put a null item in $djs on creation, meaning that if there were no running jobs, $djs would still have a count of one! I fixed this by changing the test:

    if ($djs[0] -ne $null)

    Meaning, if the first entry in $djs is not a null object, then proceed.

The full script follows:

#uasm_jobQueue.ps1, 2011-09-30, author: J. Greg Mackinnon
#Tests performance of disk when accessed by Networker backup commands.
#   Creates a queue of directories to test ($q), then uses external command 
#   "uasm.exe" to backup these directories to null.
#Change the "$wp" variable to set the number of uasm 'worker processes' to be 
#   used during the test.
#Note: PowerShell $null object causes very high CPU utilization when used for
#   this purpose.  Instead, we call "uasm_cmd.bat" which uses the CMD.exe 'nul'
#   re-director.  'nul' does not have the same problems as $null.

set-psdebug -strict

[int] $wp = 4

# Initialize the log file:
[string] $logfile = "s:\uasm_test.log"
remove-item $logfile -Force
[datetime] $startTime = Get-Date
[string] "Start Time: " + $startTime | Out-File $logfile -Append

##Create work queue array:
# Add shared directories:
[String[]] $q = gci S:\shared | ? {$_.Attributes.tostring() -match "Directory"}`
	| sort-object -Property Name | % {$_.FullName}
# Add remaining targets to queue:
$q += 'H:\','I:\','J:\','K:\','L:\','M:\','S:\sis\','S:\software\','s:\r25\'
[int] $dc = 0			#Count of completed (done) jobs.
[int] $qc = $q.Count	#Initial count of jobs in the queue
[int] $qi = 0			#Queue Index - current location in queue
[int] $jc = 0			#Job count - number of running jobs
$jobs = @()				#Jobs array - intended to contain running PS jobs.
while ($dc -lt $qc) { # Completed jobs is less than total jobs in queue
	# Keep running jobs until completed jobs is less than total jobs in queue, 
	#  and our queue count is less than the current queue index.
	while (($jobs.count -lt $wp) -and ($qc -gt $qi)) { 
		[string] $jobName = 'qJob_' + $qi + '_';
		[string] $dir = '"' + $q[$qi] + '"'
		[string] $cmd = '& cmd.exe "/c","c:\local\scripts\uasm_cmd.bat",' + $dir
		#Start the job defined in $cmd string.  Use this rather than a pre-
		#  defined scriptblock object because this allows us to see the expanded
		#  job command string when debugging. (i.e. $jobs[0].command)
		$jobs += Start-Job -Name $jobName `
			-ScriptBlock ([scriptblock]::create($cmd))
		$qi++ #Increment the queue index.
	$djs = @(); #Completed jobs array
	$djs += $jobs | ? {$_.State -eq "Completed"} ;
	# $djs array will always have a count of at least 1.  However, if the 
	#    first entry is not empty (null), then there must be completed jobs to
	#    be retrieved.
	if ($djs[0] -ne $null) { 
		$dc += $djs.count;
		$djs | Receive-Job | Out-File $logfile -Append; #Log completed jobs
		$djs | Remove-Job -Force;
		Remove-Variable djs;
		$jobs = @($jobs | ? {$_.State -eq "Running"}); #rebuild jobs array.
	Start-Sleep -Seconds 3

# Complete logging:
[datetime] $endTime = Get-Date
[string] "End Time: " + $endTime | Out-File $logfile -Append 
$elapsedTime = $endTime - $startTime
[string] $outstr =  "Elapsed Time: " + [math]::floor($elapsedTime.TotalHours)`
	+ " hours, " + $elapsedTime.minutes + " minutes, " + $elapsedTime.seconds`
	+ " seconds."
$outstr | out-file -Append $logfile

The “uasm_cmd.bat” file called in the above code block contains the following one line:

"c:\program files\legato\nsr\bin\uasm.exe" -s %1 > nul