Posts Tagged VBScript

Script to Rename Computer During OSD

In assisting a recent customer implement an upgrade from WinXP to Win7, they requested that the names be changed to fit a new standard as part of the in-place imaging process.  In this particular case, all of the computers had a name that ended with a sequential number (1, 2, 3, …) plus an “A” tacked on at the end.  They wanted the “A” removed and for the PC name just to end with the sequential number.

This was a pretty easy fix to accomplish through a VBScript which

  1. Retrieves the active OSDComputerName task sequence variable
  2. Detects if the last letter is an “A”
  3. Truncates the name to remove the “A”
  4. Re-sets OSDComputerName to the new value

'==========================================================================
' NAME: PCNameStandardization.vbs
' AUTHOR: Nick Moseley, <a href="http://t3chn1ck.wordpress.com">http://t3chn1ck.wordpress.com</a>
' COMMENT: This script will detect if the current computer name ends with ' the letter 'A' so that it can be removed.
'==========================================================================
Option Explicit
Dim oTaskSequence, sComputerName, iNameLength
Set oTaskSequence = CreateObject ("Microsoft.SMS.TSEnvironment")

sComputerName = ucase(oTaskSequence("OSDComputerName")) iNameLength = Len(sComputerName)

If right(sComputerName,1) = "A" Then
oTaskSequence("OSDComputerName") = left(sComputerName, iNameLength-1)
  ' The echo statement is not displayed, but rather registered in SMSTS.log
wscript.echo ">>>> Set OSDComputerName from " & sComputerName & " to " & oTaskSequence("OSDComputerName")
End If

To add this into your task sequence:

  1. Put this script into a package for your general OSD Scripts
  2. Ensure you have the step to capture the computer name
    CaptureWinSettings
  3. Immediately after the capture windows settings, run the PC Standardization Script
    PCNameStandardization
  4. On whatever step you have that prompts for the PC Name, add a condition to not execute if variable OSDComputerName does not exist.  This is so that task sequence will not be held up on the other end waiting for someone to enter a PC name for one you’ve already set.
    PromptPCNameCondition
  5. Finally – ensure ConfigMgr environment is configured to automatically resolve conflicting records!  See this as to why http://t3chn1ck.wordpress.com/2013/02/14/error-initializing-client-registration-0×80040222/

,

2 Comments

VBScript Disable NIC Power Management Setting

The following VBScript will disable NIC power save features.

'==========================================================================
' NAME: SetNetworkPnPCapabilities
' AUTHOR: Nick Moseley , Archstone
' COMMENT: Parses list of available network adapters to then disable power
' save features.  For more info, see Microsoft KB837058
' VERSION HISTORY:
' 1.0 (05/09/2011) - Initial script
' 1.1 (05/10/2011) - Fixed logical bug within the If statement for Wan/Lan
' 2.0 (05/10/2011) - Added logging into registry for future inventory
' 3.0 (08/17/2011) - Commented out changes to disable NIC power save as
'  this needs to be enabled in order to support WOL
'==========================================================================
Option Explicit
Const ForAppending = 8

Dim oShell, oWMI, colNetworkAdapterItems, sNetworkAdapterReg
Set oShell = CreateObject ("WScript.Shell")
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
Set colNetworkAdapterItems = oWMI.ExecQuery ("Select * from Win32_NetworkAdapter")
sNetworkAdapterReg = "HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\"

' Logging
Dim oFSO, oVersionLog
Set oFSO = CreateObject ("Scripting.FileSystemObject")
Set oVersionLog = oFSO.OpenTextFile ("C:\Windows\Version.log", ForAppending, True)
oVersionLog.WriteLine "Configuration of Network Adapters"
oVersionLog.WriteLine "  => Started (" & Date & " " & Time & ")"

' Get all objects and take action on network adapters
Dim oItem, sIndexValue, sLomValue
For Each oItem In colNetworkAdapterItems
 If InStr(lcase(oItem.Name),"wan miniport")=0 _
   And InStr(LCase(oItem.Name),"microsoft isatap")=0 _
   And Trim(oItem.Name)<>"RAS Async Adapter" _
   And InStr(LCase(oItem.Name),"cisco")=0 Then
  If oItem.Index < 10 Then
   sIndexValue = "000" & oItem.Index
  Else
   sIndexValue = "00" & oItem.Index
  End If
  
  ' ****************************************
  ' IMPORTANT: NIC power save as needs to be enabled in order to support WOL
  ' Configure/disable Power save on NIC
  oShell.RegWrite sNetworkAdapterReg & sIndexValue & "\PnPCapabilities", "56", "REG_DWORD"
  oVersionLog.WriteLine "  => Disabled network adapter power save on device """ & oItem.Name & """"
  oVersionLog.WriteLine "     Set PnPCapabilities (dword) to 38 in " & sNetworkAdapterReg & sIndexValue
  ' ****************************************
  
  ' Configure/enable WAN/LAN switching
  sLomValue = ReadRegistryKey (sNetworkAdapterReg & sIndexValue, "LOM")
  If sLomValue<>"1"  And sLomValue<>"null" Then
   oShell.RegWrite sNetworkAdapterReg & sIndexValue & "\LOM", "1", "REG_SZ"
   oVersionLog.WriteLine "  => Enabled WAN/LAN switching on device """ & oItem.Name & """"
   oVersionLog.WriteLine "     Set LOM (string) to ""1"" in " & sNetworkAdapterReg & sIndexValue
  End If  
 End If
Next
' Set registry values for SCCM inventory
oShell.RegWrite "HKLM\Software\CompanyName\Image Info\DisabledNICPowerSave", "True", "REG_SZ"

' End
oVersionLog.WriteLine "  => Completed (" & Date & " " & Time & ")"
WScript.Quit (oVersionLog.Close)

Function ReadRegistryKey (sReadKey, sReadValue)
 On Error Resume Next
 Dim sGetValue
 sGetValue = oShell.RegRead (sReadKey & "\" & sReadValue)
 
 If Err.Number <> 0 Then
  ReadRegistryKey = "null"
 Else
  ReadRegistryKey = cstr(sGetValue)
 End If  
End Function

Leave a Comment

Standalone Imaging Solution

I’ve been in a situation a couple of times where a client was going to use a third-party vendor to image hardware offsite, but didn’t have Microsoft deployment tools (WAIK, WDS, MDT, SCCM, etc.) for deploying the standard WIM image that was created.  To work with this scenario, I developed an unattended answer file with WSIM that can be used to sysprep a computer for an image where the disk can be cloned.  This sysprep file essentially does the following items below.  Many of the items may seem “unnecessary”, but they are necessary in order to automate the majority of the deployment.

Sysprep.xml Features

  • enables the local admin account
  • removes the “copy profile” functionality
  • removes the “Get Windows Live” shortcuts
  • sets the time zone to MST
  • enables RDP
  • disables firewall notifications
  • disables the domain firewall
  • disables Windows Defender
  • disables IE accelerators
  • disables the IE first run wizard
  • enables IE compatibility mode
  • disables IE suggested sites
  • sets Windows to skip auto activation
  • disables system restore
  • sets the local language to English
  • sets the registered owner/org
  • sets Windows to automatically login as Administrator one time
  • sets the screen resolution to 1024×768
  • sets the first logon command to execute a script in C:\CompanyName
  • Hides the Windows EULA Hides the wireless network setup wizard
  • sets the default network location to “Work”
  • sets the recommended level of protection for Windows Update
  • creates taskbar links to Outlook and Word

Download sysprep.xml here!!

Next, the overall process looks like such:

  1. Automate driver installation using HP SoftPaqs and script to copy the files into C:\CompanyName\ModelName\
    1. Optionally, automate and script BIOS updates
  2. Create script named “ImageConfigTasks.vbs” (code below) to do the following items (this will run post sysprep).  Script should be copied into C:\CompanyName.  You can use the attached script as a starting point.
    1. Prompt for PC name
    2. Detect PC model and install drivers (do this next to ensure the NIC driver gets installed for the domain join)
    3. Join to domain and OU
    4. Install SCCM client
    5. Install SCEP client
    6. Restart Window
  3. Create sysprep.xml file with x64 bits which essentially allows the PC to auto logon into Windows with the admin account and launches ImageConfigTasks.  You can use the attached sample as guidance, but do not actually use this file as it was compiled for the x86 components and you need it for x64.
  4. Create a “build” task sequence which installs Windows, software, security updates, copy of the drivers into the CompanyName folder, copy of the ImageConfigTasks script, copy the sysprep.xml file
  5. Run the task sequence on a VM
  6. After completion, login to Windows and run %SYS32%\sysprep\sysprep.exe /generalize /oobe /shutdown /unattend:C:\CompanyName\sysprep.xml
    1. This will sysprep the PC’s disk for cloning.  Do not power on the PC once its shutdown!
    2. Optionally, you can creatively automate this process so that you do not need to actually login to the PC
  7. Once the PC with the cloned disk has been delivered onsite, power on the PC.  Windows will go through mini-setup to install generic devices.  Then Windows will auto logon to run the script and complete the setup process.

Download the ImageConfigTasks script here!!

Run on physical hardware

To build-out this custom solution for the vendor, do the following.

  1. Complete and “certify” the newly captured image (note: this is still in progress as of 12:15 PM today, but is looking good to complete successfully).
  2. Use the deployment task to install this image AND the hardware drivers AND any other software/configurations that did not make it into the image.  You may also want to change the task sequence to NOT join to the domain for this model so that it does not receive [junky] group policies.
  3. Once that task sequence is done, login to Windows as the local admin account.
  4. Ensure the two script files live in C:\CompanyName
  5. Run %SYS32%\sysprep\sysprep.exe /generalize /oobe /shutdown /unattend:C:\CompanyName\sysprep.xml
  6. DO NOT TURN THE COMPUTER ON.  Remove the hard drive and give to vendor.  Once a cloned PC is onsite and connected to the network, only then should the PC be turned on.  A prompt for the computer name will appear and then the custom script will execute.

While you’re in the process of testing/development, you can of course turn it on to validate the scripts execute, drivers are installed, etc.

, ,

2 Comments

VBScript to Delete HKCU values or keys

Based upon my VBScript to create HKCU registry keys and/or values, I’ve created a script that does the opposite of deleting keys and/or values.  This code was also updated to locate the default user profile path for Windows 7 (and newer).

'==========================================================================
' Author: Nick Moseley, http://t3chn1ck.wordpress.com
' Comments: This script will parse all User profiles on the computer, load their  HKCU hive,
'    then set the appropriate registry keys.
' History: '    1.0 (04/07/2009) - Initial script
'    1.1 (06/03/2009) - Added example for setting dword values based on MyITForum question
'    1.2 (06/05/2009) - Added additional comments to identify the section where to define the values to be set
'    1.3 (09/23/2010) - Corrected comment typos
'    2.0 (11/12/2012) - Changed base script to DELETE specified keys/values
'==========================================================================
Option Explicit
Const ForAppending = 8
Const HKLM = &H80000002
' ************************************************
' Configure the following values to define the HKCU keys to be deleted
' ************************************************
Const sUserKey = "\Software\SampleKey"
Const sUserKeyValueName = "SampleValueName"
' ************************************************
Dim oReg, oFSO, oFile, oUserSubkey, aUserProfiles, oShell
Dim sProfileLCase, sRegExe, sRegLoad, sRegUnload, sHiveName, sSubPath, sProfile, sValueName, sKeyPathUserProfiles, sValue, ReturnVal
Set oReg = GetObject("winmgmts:\\.\root\default:StdRegProv")
Set oShell = CreateObject ("WScript.Shell")
Set oFSO = CreateObject ("Scripting.FileSystemObject")
' Begin configuration of existing user profiles
sValueName = "ProfileImagePath"
sKeyPathUserProfiles = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
sRegExe = "C:\Windows\system32\reg.exe"
oReg.EnumKey HKLM, sKeyPathUserProfiles, aUserProfiles
' Parse all user keys
For Each oUserSubkey In aUserProfiles
    sSubPath = sKeyPathUserProfiles & "\" & oUserSubkey
    oReg.GetExpandedStringValue HKLM,sSubPath,sValueName,sValue
    sProfile = Split(sValue, "\")
    sProfileLCase = LCase(sProfile(2))
     If sProfileLCase = "system32" Then
         ' Do nothing
     ElseIf sProfileLCase = "localservice" Then
        ' Do nothing
     ElseIf sProfileLCase = "networkservice" Then
        ' Do nothing
      ElseIf sProfileLCase = "serviceprofiles" Then
        ' Do nothing
      Else
          sHiveName = "TempHive_" & sProfileLCase
      ' Load user's profile hive into a temp location
          sRegLoad = " LOAD HKLM\" & sHiveName & " """ & sValue & "\ntuser.dat"""
          oShell.Run sRegExe & sRegLoad, 0, True
         ' Call subroutine to change registry key
        SetConfigUserHive (sHiveName)
         ' Unload user's profile hive
        sRegUnload = " UNLOAD HKLM\" & sHiveName
       oShell.Run sRegExe & sRegUnload, 0, True
      End If
Next
' Default User Profile sHiveName = "TempHive_DefaultUser"
sRegLoad = " LOAD HKLM\" & sHiveName & " ""C:\Users\Default\ntuser.dat"""
oShell.Run sRegExe & sRegLoad, 0, True
SetConfigUserHive (sHiveName)
sRegUnload = " UNLOAD HKLM\" & sHiveName
oShell.Run sRegExe & sRegUnload, 0, True
' End script
WScript.Quit ()
Sub SetConfigUserHive (sTempHive)
    Dim sTempHiveKeyPath
    ' Path of registry keys
    sTempHiveKeyPath = sTempHive & sUserKey
   'wscript.echo "sHiveName = " & sTempHiveKeyPath
    ' Delete value
    ReturnVal = oReg.DeleteValue(HKLM, sTempHiveKeyPath & "\", sUserKeyValueName)
     ' Delete key
     ReturnVal = oReg.DeleteKey(HKLM, sTempHiveKeyPath & "\", sUserKey)
End Sub

10 Comments

ConfigMgr Client GPO Assignment Removal

On a recent upgrade project of ConfigMgr 2007 to 2012, the company I was assisting with the upgrade had previously deployed a group policy to enforce the client assignment to the 2007 site code.  However, simply removing the GPO could not correct the situation as the value was “tattooed” into the registry.  So as part of the ConfigMgr client upgrade, I included the below script to revoke the registry key.


' ***********************************************************
' This script was created by <a href="http://t3chn1ck.wordpress.com/">http://t3chn1ck.wordpress.com</a> to 
' delete the following registry value. The value will prevent 
' the abilityof anSCCM client to become reassigned to the new
' ConfigMgr 2012 site.
' HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SMS\Mobile Client\
' GPRequestedSiteAssignmentCode (REG_SZ) = ""
' ***********************************************************
Option Explicit
Const HKLM = &H80000002 Const sRegKey = "SOFTWARE\Microsoft\SMS\Mobile Client"
Const sRegValueName = "GPRequestedSiteAssignmentCode"
Dim oReg, iReturnValue
Set oReg = GetObject("winmgmts:\\.\root\default:StdRegProv")
iReturnValue = oReg.SetStringValue (HKLM, sRegKey, sRegValueName, "")
wscript.quit iReturnValue

, ,

10 Comments

Script to Convert XLS to XLSX

Wrote this little diddy to convert an Excel 2003 file to Excel 2010 file.


' http://technet.microsoft.com/en-us/library/ff198017.aspx
Const xlExcel12 = 50
Set oExcel = CreateObject("Excel.Application")

' Set below value to false to hide the Excel window
oExcel.Visible = True

' Convert
Set oWorkbook = oExcel.Workbooks.Open("C:\filename.xls")
Set oWorksheet = oWorkbook.Worksheets(1)
oWorkbook.SaveAs "C:\filename.xlsb", xlExcel12 

' End
oExcel.quit (oWorkbook.Close)

Leave a Comment

Creating Faxination Printer for Windows

Faxination is product that is commonly used for performing electronic faxing.  I recently needed to create an automated/unattended installation of the Faxination ”printer” such that user can print a document to that “printer” which converts the file to an image an composes an Outlook email for sending the fax. Unfortunately the product does not have an installer for this printer creation in Windows, so I had to develop a custom solution.

High-level overview

  1. Registers PrnAdmin.dll (which enables scripting printer operations in Windows)
  2. Creates a new Windows printer port
  3. Copies into Program Files the Faxination drivers and a script which registers the printer for the user.
  4. Uses the built-in Windows PrnDrv commands to add the driver
  5. Creates a Run key for ever user who logs into Windows to execute the aforementioned user script, which uses the built-in Windows PrnMngr commands to add the printer for the user (and also retains the prior default printer)

To set this up in a package

  1. Obtain the latest Faxination drivers from Fenestrae support
  2. Obtain PrnAdmin.dll from the Windows Server 2003 Resource Kit Tools
  3. Obtain Setup_x86.vbs from SkyDrive http://sdrv.ms/O9Odds
  4. Obtain CreateFaxinationPrinter.vbs from SkyDrive http://sdrv.ms/NCetyx
  5. For the package source files, in the root folder, add “Setup_x86.vbs” and PrnAdmin.dll
  6. Create a subfolder named “x86″ and add the Faxination driver files and the “CreateFaxinationPrinter.vbs” script
  7. Create the package and advertise to computers to test!

Leave a Comment

VBScript to delete Novell registry keys

Recently I created a script for a colleague that will recursively delete some Novell registry keys if found in HKEY_USERS.  It doesn’t check if the key exists first, it’ll just try to delete it.  However, if the key does exist and does have subkeys, it will delete the subkeys first. Hopefully this will get the job done if you need something like this.  To test it first, simply uncomment the wscript.echo statements and run on a test system.

'On Error Resume Next 
Const HKU = &H80000003 
Set objRegistry = GetObject("winmgmts:\\.\root\default:StdRegProv") 
' Delete first key strKeyPath = "Software\Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Novell GroupWise" objRegistry.EnumKey HKU, "", arrSubkeys1 
For Each strSubkey in arrSubkeys1 'wscript.echo cstr(strSubkey) DeleteSubkeys HKU, cstr(strSubkey) & "\" & strKeypath  Next 
' Delete second key strKeyPath = "Microsoft\Windows NT\CurrentVersion\Windows Messaging Subsystem\Profiles\Novell Default Settings" objRegistry.EnumKey HKU, "", arrSubkeys2 
For Each strSubkey in arrSubkeys2 'wscript.echo cstr(strSubkey) DeleteSubkeys HKU, cstr(strSubkey) & "\" & strKeypath  Next 
wscript.quit 0 
'============================================================ 
Sub DeleteSubkeys(HKU, strKeyPath) 
   objRegistry.EnumKey HKU, strKeyPath, arrSubkeys3 
   If IsArray(arrSubkeys3) Then For Each strSubkey In arrSubkeys3 DeleteSubkeys HKU, strKeyPath & "\" & strSubkey  Next End If 
   objRegistry.DeleteKey HKU, strKeyPath z  'wscript.echo "Deleted: " & strKeyPath 
End Sub

Leave a Comment

Hiding a task sequence progress UI

If you have a custom HTA or dialog box as part of a task sequence, the dialog box could get in the way.  And it’s quite annoying to manually drag it out-of-the-way every time.   A workaround to this is to hide that task sequence dialog box altogether with the following VBScript.  So run this bit of code before you launch the HTA

On Error Resume Next
' Hide the task sequence window 
Set ProgressUI = CreateObject("Microsoft.SMS.TsProgressUI") 
ProgressUI.CloseProgressDialog

,

Leave a Comment

VBScript to Run SCCM Software Updates Scan

A challenge with installing software updates during a task sequence is that it may occur where not all updates are applied on the first pass.   The workaround is run software updates, run a VB Script or PowerShell script to force another scan, then run a software updates task again.  Others have posted their scripts on this before, so it’s nothing new.  However, I failed trying to quickly locate those scripts.  So I’m just posting my own of what I use….

'==========================================================================
' AUTHOR: Nick Moseley , http://t3chn1ck.wordpress.com
' DATE  : 7/30/2010

' COMMENT: Initiates an SCCM client scan
' Script from http://msdn.microsoft.com/en-us/library/cc144313.aspx
' Updated 7/15/11 to include a sleep before exiting script
'==========================================================================
' Set the required variables. 
actionNameToRun = "Updates Source Scan Cycle"
' Create a CPAppletMgr instance.
Dim oCPAppletMgr
Set oCPAppletMgr = CreateObject("CPApplet.CPAppletMgr")
' Get the available ClientActions object.
Dim oClientActions
Set oClientActions = oCPAppletMgr.GetClientActions()
' Loop through the available client actions. Run the matching client action when it is found.
Dim oClientAction
For Each oClientAction In oClientActions
 If oClientAction.Name = actionNameToRun Then
  oClientAction.PerformAction  
 End If
Next
' Wait for 3 minutes for scan completion before exiting script
wscript.sleep(180000)

, , ,

6 Comments

Follow

Get every new post delivered to your Inbox.

Join 59 other followers