VBS Script – Get Computer Serial Number Remotely

The following script can be used to remotely access the serial number for a computer on your network.

Output:

When you run the script it will prompt for the computer name:

VBS-GetSerialNumber1

After entering the computer name and pressing ‘OK’ it will return the part number, serial number and asset tag. (if saved to the systems BIOS).

The serial number is presented in a text box which allows you to copy and paste it into another window.

VBS-GetSerialNumber2

VBS Script:

Download

MyHostName = InputBox ("Enter Machine Name")
Set objWMIService = GetObject("winmgmts:" _
            & "{impersonationLevel=impersonate}!\\" & MyHostName & "\root\cimv2")
Set colSMBIOS = objWMIService.ExecQuery _
            ("Select * from Win32_SystemEnclosure")
  For Each objSMBIOS in colSMBIOS            
    pn = "Part Number: " & objSMBIOS.PartNumber
    sn = "Serial Number: " & objSMBIOS.SerialNumber
    sn1 =  objSMBIOS.SerialNumber
    an = "Asset Tag: " & objSMBIOS.SMBIOSAssetTag
  Next
tmp = InputBox (pn & VBCrLf & sn  & VBCrLf & an,"Computer Serial Number",sn1)

VBS Script – Get Monitor Serial Number Remotely

The following script will remotely connect to a computer on your network, query the registy for the monitor details and output what it finds.

It can be used to remotely get the monitor make, model and serial number from any computer on your network.

There are two versions of the script available, one for a single computer or one for a list of computers.

Get monitor serial number for a single computer

Output:

Download: Get Monitor Info – remotely.vbs

When you run the script it will prompt for the remote computer name:

VBS-GetMonitorDetails1

After entering the remote computer name it will return the information on the attached monitors.

This computer has two monitors, so the information is separated by [Monitor_1] and [Monitor_2]

VBS-GetMonitorDetails2

 

Get monitor serial number for a list of computers

Note – you require Microsoft Excel installed on the computer are you running this script.

Download: VBS – Get Monitor Serial Number Remotely – Machine List.zip

  1. After downloading and extracting the ZIP file you will find two files,
    1. MachineList.txt – which holds the list of computers to get the serial numbers from, each computer name needs to be on a new line
    2. Get_Monitor Info – remotely (MachineList).vbs – the script to run
  2. Update MachineList with the list of computers
  3. Run ‘Get_Monitor Info – remotely (MachineList).vbs’
  4. Microsoft Excel will load and begin to add the header row then the details of each computer
  5. If a computer is online (available on the network) its details will be recorded then it is removed from MachineList.txt
  6. If a computer is offline it is marked as ‘Offline’ in the excel document and it remains in MachineList, so you can run the script later when the computer is online.

VBS-GetMonitor1

VBS Script – Get USB Drive Serial Number

Many USB drives (particularly USB ‘thumb drives’) do not have the unique serial number printed on the outside.

Sometimes there is a need to use the unique hardware serial number for asset record management or auditing.

The following script can be used to get the serial number for a USB Drive (or hard drive).

Output:

When you run the script it will prompt for the drive letter (e.g. E)

VBS-USBDetails1

After entering the ldrive letter and clicking ‘OK’ it will return the serial number for the device.

It will also return the drive type, file system, free space (in MB) and total size (in MB).

The serial number is presented in a text box which allows you to copy and paste it into another window.

VBS-USBDetails2

VBS Script:

strComputer = "."
usbdrive = InputBox ("Enter the USB Drive Letter")
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
str = ""
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_LogicalDisk Where DeviceID ='" & usbdrive & ":'")
For Each objItem In colItems
   SerialNumber = objItem.VolumeSerialNumber
   DriveType = objItem.Description
   FileSystem = objItem.FileSystem
   FreeSpace = (objItem.FreeSpace / 1048576)
        FreeSpace=Round(FreeSpace,2)
   TotalSize = (objItem.Size / 1048576)
        TotalSize=Round(TotalSize,2)


Next

tmp = inputBox ("Drive Type:  " & DriveType & vbNewLine & "File System:  " & FileSystem & vbNewLine & "Free Space:  " & FreeSpace & "   MB"  & vbNewLine & "Total Size:  " & TotalSize & "   MB" , "USB Drive Serial Number",SerialNumber)

VBS Script – Get Dell Service Tag Remotely

The following VBS Script can be used to remotely get the Dell Service Tag from another computer on your network.

Output:

When you run the script it will prompt for the remote computer name:

VBS-GetDellServiceTag1

After entering the computer name and clicking ‘OK’ it will return a prompt which includes the Dell Service Tag:

VBS-GetDellServiceTag2

VBS Script:

on error resume next
strComputer=InputBox ("Enter the computer name of the server you'd like to query for Service Tag")
Set objWMIservice = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
set colitems = objWMIservice.ExecQuery("Select * from Win32_BIOS",,48)
For each objitem in colitems
Wscript.echo "Dell Service Tag: " & objitem.serialnumber
Next

VBS Script – Check for Locked Active Directory User Accounts

The following VBS Script will check your Active Directory environment for user accounts which are currently locked out.

This could be used to assist with diagnosing accounts which are repetitively being locked.

Output:

If there are no accounts locked out it will return “No user accounts locked out in domain.”

VBS-LockedAccounts1

If there are accounts locked out it will return a prompt for each locked out account. It will also indicate the time and date when the account was locked out.

VBS-LockedAccounts2

VBS Script:

' Hilltop Lab web site - http://www.rlmueller.net

Option Explicit

Dim objRootDSE, strConfig, adoConnection, adoCommand, strQuery
Dim adoRecordset, objDC
Dim strDNSDomain, objShell, lngBiasKey, lngBias, k, arrstrDCs()
Dim strDN, dtmDate, objDate, strUser, strNTName
Dim objList1, objList2, objList3, j, intBadCount
Dim strBase, strFilter, strAttributes, objWinNTUser
Dim objTrans, strNetBIOSDomain, objDomain, arrstrNTNames()
Dim lngHigh, lngLow

‘ Constants for the NameTranslate object.
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

‘ Determine DNS domain name.
Set objRootDSE = GetObject(“LDAP://RootDSE”)
strDNSDomain = objRootDSE.Get(“defaultNamingContext”)

‘ Use the NameTranslate object to convert the DNS domain name
‘ to the NetBIOS domain name.
Set objTrans = CreateObject(“NameTranslate”)
objTrans.Init ADS_NAME_INITTYPE_GC, “”
objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain
strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)
‘ Remove trailing backslash.
strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) – 1)

‘ Find locked out user accounts in domain
‘ create array of sAMAccountName’s
Set objDomain = GetObject(“WinNT://” & strNetBIOSDomain)
objDomain.Filter = Array(“user”)
k = 0
For Each objWinNTUser In objDomain
If (objWinNTUser.IsAccountLocked = True) Then
ReDim Preserve arrstrNTNames(k)
arrstrNTNames(k) = objWinNTUser.name
k = k + 1
End If
Next

If (k = 0) Then
Wscript.Echo “No user accounts locked out in domain”
Wscript.Quit
End If

‘ Use dictionary objects to track latest badPasswordTime,
‘ badPwdCount, and Domain Controller for each locked out user.
Set objList1 = CreateObject(“Scripting.Dictionary”)
objList1.CompareMode = vbTextCompare
Set objList2 = CreateObject(“Scripting.Dictionary”)
objList2.CompareMode = vbTextCompare
Set objList3 = CreateObject(“Scripting.Dictionary”)
objList3.CompareMode = vbTextCompare

‘ Obtain local Time Zone bias from machine registry.
‘ This bias changes with Daylight Savings Time.
Set objShell = CreateObject(“Wscript.Shell”)
lngBiasKey = objShell.RegRead(“HKLM\System\CurrentControlSet\Control\” _
& “TimeZoneInformation\ActiveTimeBias”)
If (UCase(TypeName(lngBiasKey)) = “LONG”) Then
lngBias = lngBiasKey
ElseIf (UCase(TypeName(lngBiasKey)) = “VARIANT()”) Then
lngBias = 0
For k = 0 To UBound(lngBiasKey)
lngBias = lngBias + (lngBiasKey(k) * 256^k)
Next
End If

‘ Determine configuration context.
strConfig = objRootDSE.Get(“configurationNamingContext”)

‘ Use ADO to search Active Directory for ObjectClass nTDSDSA.
‘ This will identify all Domain Controllers.
Set adoCommand = CreateObject(“ADODB.Command”)
Set adoConnection = CreateObject(“ADODB.Connection”)
adoConnection.Provider = “ADsDSOObject”
adoConnection.Open = “Active Directory Provider”
adoCommand.ActiveConnection = adoConnection

strBase = “<LDAP://” & strConfig & “>”
strFilter = “(objectClass=nTDSDSA)”
strAttributes = “AdsPath”
strQuery = strBase & “;” & strFilter & “;” & strAttributes & “;subtree”

adoCommand.CommandText = strQuery
adoCommand.Properties(“Page Size”) = 100
adoCommand.Properties(“Timeout”) = 60
adoCommand.Properties(“Cache Results”) = False

Set adoRecordset = adoCommand.Execute

‘ Enumerate parent objects of class nTDSDSA. Save Domain Controller
‘ DNS host names in dynamic array arrstrDCs.
k = 0
Do Until adoRecordset.EOF
Set objDC = _
GetObject(GetObject(adoRecordset.Fields(“AdsPath”).Value).Parent)
ReDim Preserve arrstrDCs(k)
arrstrDCs(k) = objDC.DNSHostName
k = k + 1
adoRecordset.MoveNext
Loop
adoRecordset.Close

‘ Use ADO to retrieve all user objects from each Domain Controller.
strFilter = “(&(objectCategory=person)(objectClass=user))”
strAttributes = “distinguishedName,sAMAccountName,” _
& “badPasswordTime,badPwdCount”
For k = 0 To Ubound(arrstrDCs)
strBase = “<LDAP://” & arrstrDCs(k) & “/” & strDNSDomain & “>”
strQuery = strBase & “;” & strFilter & “;” & strAttributes _
& “;subtree”
adoCommand.CommandText = strQuery
On Error Resume Next
Set adoRecordset = adoCommand.Execute
If (Err.Number <> 0) Then
On Error GoTo 0
Wscript.Echo “Domain Controller not available: ” & arrstrDCs(k)
Else
On Error GoTo 0
Do Until adoRecordset.EOF
strNTName = adoRecordset.Fields(“sAMAccountName”).Value
‘ Check each user to see if in array of locked out accounts.
For j = 0 To UBound(arrstrNTNames)
If (UCase(strNTName) = UCase(arrstrNTNames(j))) Then
‘ User locked out, retrieve badPasswordTime.
strDN = adoRecordset.Fields(“distinguishedName”).Value
intBadCount = adoRecordset.Fields(“badPwdCount”).Value
On Error Resume Next
Set objDate = adoRecordset.Fields(“badPasswordTime”).Value
If (Err.Number <> 0) Then
On Error GoTo 0
dtmDate = #1/1/1601#
Else
On Error GoTo 0
lngHigh = objDate.HighPart
lngLow = objDate.LowPart
If (lngLow < 0) Then
lngHigh = lngHigh + 1
End If
If (lngHigh = 0) And (lngLow = 0) Then
dtmDate = #1/1/1601#
Else
dtmDate = #1/1/1601# + (((lngHigh * (2 ^ 32)) _
+ lngLow)/600000000 – lngBias)/1440
End If
End If
If (objList1.Exists(strDN) = True) Then
If (dtmDate > objList1.Item(strDN)) Then
‘ Later badBadPasswordTime found, save info from this DC.
objList1.Item(strDN) = dtmDate
objList2.Item(strDN) = intBadCount
objList3.Item(strDN) = arrstrDCs(k)
End If
Else
‘ First time user found, save info from this DC.
objList1.Add strDN, dtmDate
objList2.Add strDN, intBadCount
objList3.Add strDN, arrstrDCs(k)
End If
End If
Next
adoRecordset.MoveNext
Loop
adoRecordset.Close
End If
Next

‘ Output information on each locked out user.
For Each strUser In objList1.Keys
Wscript.Echo strUser & ” ; ” & objList1.Item(strUser) & ” ; ” _
& objList2.Item(strUser) & ” ; ” & objList3.Item(strUser)
Next

‘ Clean up.
adoConnection.Close

VBS Script – Remotely Enable Remote Desktop (RDP)

The following VBS Script can be used to remotely ENABLE or DISABLE Remote Desktop (RDP).

It is compatible with Windows 7 systems.

Whilst Group Policy is the recommended method for configuring Remote Desktop on multiple systems, this script may come in handy when you need to immediately configure RDP on a particular system.

How it works:

When you run the script it will prompt for the computer machine name (network name)

VBS-EnableRDP1

It will then display whether it is currently ENABLED or DISABLED and ask if you want to change this.

VBS-EnableRDP2

Download: here (note, you will need to rename as a .vbs file)

VBS Script:

' This script will enable or disable remote desktop  on a remote system
' Pat Fiannaca

const HKEY_LOCAL_MACHINE = &H80000002
strComputer = InputBox("Enter the MACHINE NAME on which you would like to enable or disable Remote Desktop:")

If strComputer = "" Then
  WScript.Quit
End If

Set StdOut = WScript.StdOut

On Error Resume Next

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_ 
strComputer & "\root\default:StdRegProv")
If Err.Number <> 0 Then
  WScript.Echo "An error has occurred.  You may have mistyped the computer name." 
  WScript.Quit
End If

strKeyPath = "SYSTEM\CurrentControlSet\Control\Terminal Server"
strValueName = "fDenyTSConnections"

oReg.GetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue

If dwValue = 1 Then
  prompt = MsgBox ("Remote Desktop is Currently disabled.  Do you want to ENABLE it?", vbYesNo)
  If prompt = vbYes then
    dwValue = 0
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue 
     WScript.Echo "Remote Desktop is now ENABLED on " & strComputer
    WScript.Quit
  ElseIf prompt = vbNo then
    WScript.Echo "Remote Desktop is still DISABLED."
   Wscript.Quit 
  End If
ElseIf dwValue = 0 then
  prompt = MsgBox ("Remote Desktop is Currently ENABLED.  Do you want to DISABLE it?", vbYesNo)
  If prompt = vbYes then
    dwValue = 1
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,dwValue
    WScript.Echo "Remote Desktop is now DISABLED on " & strComputer
    WScript.Quit
  ElseIf prompt = vbNo then
    WScript.Echo "Remote Desktop is still ENABLED." 
    WScript.Quit
  End If
End If

Source: http://community.spiceworks.com/scripts/show/302-enable-or-disable-rdp-remote-desktop-on-remote-system-vbs 

Windows 7 – VBS script to change last user logged on user

The following VBS script will change the last user logged on user for a Windows 7 workstation.

This script has been used with Windows 7 workstation which is on an Active Directory domain.

MSWin7-LogonScreen1

Some background:

With Windows XP you used to be able to edit the registry information under ‘Winlogon’ (see: Using VBS to set the last user logged on (Windows XP))

However, Windows 7 no longer uses this registry information for the last logged on user, it now uses:

"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\LastLoggedonUser"

Additionally, this section of the registry requires elevated rights to modify, however if you run a VBS Script by double clicking it is not elevated.

To fix this, I was able to find a workaround to make the script run as an elevated user (see: Windows 7 – Run VBS script as elevated user (UAC))

Set Last Loggedon – Win7.vbs

To use the script, copy the following code into a new text file and save as ‘Set Last Loggedon – Win7.vbs’, run the script and enter in the required username. If it is a local uer account leave the domain blank.

Full Download: here

'--------------
'Start of UAC workaround code

If WScript.Arguments.length =0 Then
Set objShell = CreateObject("Shell.Application")

objShell.ShellExecute "wscript.exe", Chr(34) & _
WScript.ScriptFullName & Chr(34) & " uac", "", "runas", 1
Else

'--------------
'Start of code

dim WSHShell
Set WSHShell = Wscript.CreateObject("WScript.Shell")
dim strRegKey
strComputerName = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )
strRegKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\"

StrUser = InputBox("Please enter in username," & vbCrLf & vbCrLf & "e.g. joe.local", "Set Last logged on", "UserName")
StrDomain = InputBox("Please enter in domain for logon," & vbCrLf & vbCrLf & "e.g. DOMAIN", "Set Logon Domain OR leave blank if a local user account")

If StrDomain = "" then
StrDomain = "."
Else
End If

wshShell.RegWrite strRegKey & "LastLoggedOnUser", StrDomain & "\" & StrUser, "REG_SZ"

WScript.Echo "Setup Completed. Please restart the computer to complete the process"

'--------------
'End of code

'--------------
'End of UAC workaround code

End If 

VBS Script – Count Number of times computer has turned on

The following scripts can be used to count the number of times a computer has been turned on.

It queries the ‘Sytem’ event log for Event 12 which is ‘The operating system started at system time ?2011?-?05?-?16T05:28:24.359599800Z’

It then counts the number of Event 12’s and echos the number.

The second script can be used on remote computers as long as you have the appropriate Administrator rights on the machine.

To use the scripts you wil need to copy into a text document and save the file is a .vbs extension.

You can also download from here

 

 Count number of times computer has turned on:

Output:

VBS-CountStarted2

VBS Code:

count = 0
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colLoggedEvents = objWMIService.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = 'System'" _
& " and EventCode = '12'")

For Each objEvent in colLoggedEvents
count = count + 1

Next

wscript.echo "Number of times operating system has started:   " & count

 

Remotely count number of times computer has turned on:

Output:

VBS-CountStarted1

VBS-CountStarted2

VBS Code:

count = 0
strComputer=InputBox ("Enter the network name for the remote computer")
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colLoggedEvents = objWMIService.ExecQuery _
("Select * from Win32_NTLogEvent Where Logfile = 'System'" _
& " and EventCode = '12'")

For Each objEvent in colLoggedEvents
count = count + 1

Next

wscript.echo "Number of times operating system has started:   " & count 

VBS Script – Uninstall Java Runtime

The following script can be used to uninstall all versions of Java on a computer.

Please note:

Warning:

Uninstalling Java can be troublesome. Some version do not want to be uninstalled silently (e.g. by a script or command) and some may half uninstall resulting in a somewhat impaired computer. I strongly suggest you thoroughly test this script in your environment before deploying to production computers.

How do I use the script?

Copy it into notepad and save the file as JavaUninstallScript.vbs

  • If running on the local computer
    1. Open the command line as Administrator (Right click on ‘Command Prompt’ in the start menu and select ‘Run as Administrator’)
    2. Navigate to where the HavaUninstallScript.vbs was saved to
    3. Run the command which best suits you
  • If running from Configuration Manager (ConfigMgr /  SCCM)
    1. Copy the script to your package share
    2. Create the package
    3. Set the program command as
cscript /nologo JavaUninstallScript.vbs /keeponly

For more information on creating SCCM packages see distribute software using SCCM.

 

Usage Examples:

Removes all Java Runtimes without creating logs

cscript /nologo JavaUninstallScript.vbs /keeponly

Removes all Java Runtimes found except Java 6 Update 24 and J2SE 5 Update 16 and places the uninstall logs in C:Temp

cscript /nologo JavaUninstallScript.vbs /keeponly /versions:"Java(TM) 6 Update 24;J2SE Runtime Environment 5.0 Update 16" /logfilepath:"C:Temp"

Removes all Java Runtimes found except x64 Java 6 Update 24 and x86 J2SE 5 Update 16 on a x64 system and places the uninstall logs in C:Temp

cscript /nologo JavaUninstallScript.vbs /keeponly /versions:"Java(TM) 6 Update 24" /versionsx86onx64:"J2SE Runtime Environment 5.0 Update 16" /logfilepath:"C:Temp"

Keeps all Java Runtimes. Only useful for making a list of installed runtimes

cscript /nologo JavaUninstallScript.vbs /removeonly

JavaUninstallScript.vbs Script

'***************************************************************************************
'Java removal script.
'Version: 3.0
'Description: Removes specified Java versions based on command line parameters.
'                        !!!!!!USE AT YOUR OWN RISK!!!!!!!
'2011.03.09 - 2.0 - First version. Assumes %SYSTEMDRIVE%\Logs exists.
'2011.03.23 - 2.1 - Fixes issue running in 32bit SCCM under 64bit Windows.
'2011.03.30 - 2.2 - Adds array of versions to keep.
'2011.04.24 - 3.0 - Added command line parameters. Still doesn't make the log directory!
'***************************************************************************************
'-----------------------------Begin Main Script--------------------------------
Option Explicit

'If help is specified on the command line, show it and quit.
If WScript.Arguments.Named.Count < 1 Or WScript.Arguments.Named.Exists("help") Or WScript.Arguments.Named.Exists("?") Then    PrintHelp()    WScript.Quit(0) End If Dim aryVersions, aryVersionsx86Onx64 Dim bolKeepJava Dim colNamedArguments, colProcesses Dim objWMIService, objProcessor, objProcess Dim strArgument, strLogFilePath 'Set default command line parameters. 'The script defaults to removing all versions of Java without leaving uninstall logs. bolKeepJava = 1 strLogFilePath = "" aryVersions = Array() aryVersionsx86Onx64 = Array() 'Start script logging. WScript.Echo "**********************************" WScript.Echo "Java uninstall script started at " & Now() 'Parse command line parameters. If WScript.Arguments.Named.Count > 0 Then
   Set colNamedArguments = WScript.Arguments.Named

   For Each strArgument in colNamedArguments
       Select Case LCase(strArgument)
           Case "keeponly"
           Case "removeonly"
               bolKeepJava = 0
           Case "logfilepath"
               strLogFilePath = colNamedArguments.Item(strArgument)
           Case "versions"
               aryVersions = Split(colNamedArguments.Item(strArgument), ";", -1, 1)
           Case "versionsx86onx64"
               aryVersionsx86Onx64 = Split(colNamedArguments.Item(strArgument), ";", -1, 1)
           Case Else
               WScript.Echo vbCrLf & "Unknown switch: " & strArgument & "."
               WScript.Echo vbCrLf & "Java uninstall script finished at " & Now()
               WScript.Echo "**********************************" & vbCrLf
               PrintHelp()
               WScript.Quit(2)
       End Select
   Next
End If

'Output the parameters the script was run with.
WScript.Echo vbCrLf & "----------------------------------"
WScript.Echo "Script parameters:"
   If bolKeepJava Then
       WScript.Echo "Specified Java versions found will be kept. Other versions will be removed."
   Else
       WScript.Echo "Specified Java versions found will be removed. Other versions will be kept."
   End If
   
   'This check is important. It will default the versions array if no versions were specified. Without this the whole thing falls apart.
   If (Ubound(aryVersions) < 0 ) Then
       aryVersions = Array("FooBar")
       WScript.Echo "No native Java versions specified on the command line."
   Else
       WScript.Echo "Native Java versions specified on the command line."
   End If
   
   'If no non-native versions are specified set the non-native array to the native array.
   If (Ubound(aryVersionsx86Onx64) < 0) Then
       aryVersionsx86Onx64 = aryVersions
       WScript.Echo "No x86 Java versions for x64 systems specified on the command line." & vbCrLf & "Using specified native verions for x86 also."
   Else
       WScript.Echo "x86 Java versions for x64 systems specified on the command line."
   End If
   
   If strLogFilePath = "" Or IsNull(strLogFilePath) Then
       WScript.Echo "Uninstall logfile path is empty. Uninstall logs will not be created."
   Else
       'If the log file path does not end in a \ put one on there!
       If (StrComp(Right(strLogFilePath,1), "\") <> 0) Then
           strLogFilePath = strLogFilePath & "\"
       End If
       WScript.Echo "Uninstall log file path: " & strLogFilePath & "."
   End If
WScript.Echo "----------------------------------"

'Get a WMI Service object.
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate, (Debug)}\\.\root\cimv2")

'Get processor object. objProcessor.AddressWidth will give us bitness. Check objProcessor.AddressWidth = "32" or "64"
Set objProcessor = GetObject("winmgmts:\\.\root\cimv2:Win32_Processor='cpu0'")

'Kill processes that might prevent installs or uninstalls.
Set colProcesses = objWMIService.ExecQuery("Select Name from Win32_Process Where Name = 'jqs.exe' OR Name = 'jusched.exe' OR Name = 'jucheck.exe' OR Name = 'jp2launcher.exe' OR Name = 'java.exe' OR Name = 'javaws.exe' OR Name = 'javaw.exe'", "WQL", 48)

WScript.Echo vbCrLf & "----------------------------------"
WScript.Echo "Checking for problematic processes."

'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 objProcess in colProcesses

   WScript.Echo "Found process " & objProcess.Name & "."

   objProcess.Terminate()

   Select Case Err.Number
       Case 0
           WScript.Echo "Killed process " & objProcess.Name & "."
           Err.Clear
       Case -2147217406
           WScript.Echo "Process " & objProcess.Name & " already closed."
           Err.Clear
       Case Else
           WScript.Echo "Could not kill process " & objProcess.Name & "! Aborting Script!"
           WScript.Echo "Error Number: " & Err.Number
           WScript.Echo "Error Description: " & Err.Description
           WScript.Echo "Finished problematic process check."
           WScript.Echo "----------------------------------"
           WScript.Echo vbCrLf & "Java uninstall script finished at " & Now()
           WScript.Echo "**********************************" & vbCrLf
           WScript.Quit(1)
   End Select
   
Next

'Resume normal error handling.
On Error Goto 0

WScript.Echo "Finished problematic process check."
WScript.Echo "----------------------------------"

'This call will remove x64 versions on a x64 system and x86 versions on a x86 system.
RemoveJava "Software\Microsoft\Windows\CurrentVersion\Uninstall\", aryVersions, strLogFilePath, objProcessor

'This call will remove x86 versions on a x64 system.
If (objProcessor.AddressWidth = "64") Then
   RemoveJava "Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\", aryVersionsx86Onx64, strLogFilePath, objProcessor
End If

WScript.Echo vbCrLf & "Java uninstall script finished at " & Now()
WScript.Echo "**********************************" & vbCrLf
'-------------------------------End Main Script--------------------------------

'---------------------------------Functions------------------------------------
Function RemoveJava(strRegistryPath, aryVersions, strLogFilePath, objProcessor)

   Dim objWSHShell, objRegistry, objWbemContext, objSWbemLocator, objSWbemServices
   Dim aryUninstallKeys
   Dim strUninstallKey, strDisplayName, strUninstallString, strVersion
   Dim intUninstallReturnCode

   Set objWSHShell = CreateObject("WScript.Shell")
   
   'The following SWbem setup allows a script running in a x86 context, such as under the SCCM client, on a x64 system
   'to access the full x64 registry. Without this the actual registry paths will be transparently redirected to the
   'Wow6432Node branch for every registry call to HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall.
   'Essentially this transparent redirection would hide 64bit Java runtimes from a script running in 32bit mode on a 64bit OS.
   
   'Provides the bitness context parameters for registry calls.
   Set objWbemContext = CreateObject("WbemScripting.SWbemNamedValueSet")
   objWbemContext.Add "__ProviderArchitecture", objProcessor.AddressWidth
   objWbemContext.Add "__RequiredArchitecture", true
   
   'Create SWbemLocator to connect to WMI
   Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
   
   'Actually connect to the WMI service using the SWbemLocator and the SWbemContext parameters.
   Set objSWbemServices = objSWbemLocator.ConnectServer(".","root\default","","",,,,objWbemContext)
   
   'Get the Standard Registry Provider from WMI... finally.
   Set objRegistry = objSWbemServices.Get("StdRegProv")

   'Find the Java uninstallers hiding in the uninstall key. &H80000002 = HKEY_LOCAL_MACHINE for this function call.
   objRegistry.EnumKey &H80000002, strRegistryPath, aryUninstallKeys
   
   'Enable VBS' poor excuse for error handling...
   On Error Resume Next
   
   For Each strUninstallKey In aryUninstallKeys
   
       'These must be reset in case the GetStringValue fails to return a value. This way we don't keep values for other pieces of software.
       strDisplayName = ""
       strUninstallString = ""
       intUninstallReturnCode = ""
       
       'DisplayName should always be a REG_SZ
       objRegistry.GetStringValue &H80000002, strRegistryPath & strUninstallKey, "DisplayName", strDisplayName
       
       'Just in case GetStringValue doesn't retrieve what we want.
       If Err.Number <> 0 Then
           Wscript.Echo vbCrLf & "----------------------------------"
           WScript.Echo "Could not retrieve DisplayName at " & strRegistryPath & strUninstallKey & "!"
           WScript.Echo "Error Number: " & Err.Number
           WScript.Echo "Error Description: " & Err.Description
           Wscript.Echo "----------------------------------"
           strDisplayName = ""
           Err.Clear
       End If
       
       'In English: If the DisplayName contains either Java OR the DisplayName contains J2SE Runtime Environment
       'AND if the DisplayName does not contain Development AND if the DisplayName does not contain JavaDB
       'AND if the DisplayName does not contain Web Start
       'AND if the DisplayName does not contain SAS
       'AND if the DisplayName does not contain Java Auto Update then do the if block.
       'Fun, eh?
       'You could remove the Web Start line to get rid of JWS but the uninstall string If block would have to account for that. It currently doesn't.
       
       If ((Instr(1, strDisplayName, "Java", 1) OR (Instr(1, strDisplayName, "J2SE Runtime Environment", 1))) _
           AND ((Instr(1, strDisplayName, "Development", 1) + Instr(1, strDisplayName, "JavaDB", 1)) < 1)  _
           AND (Instr(1, strDisplayName, "Web Start", 1) < 1) _
           AND (Instr(1, strDisplayName, "SAS", 1) < 1) _
           AND (Instr(1, strDisplayName, "Java Auto Update", 1) < 1)) Then
           
           Wscript.Echo vbCrLf & "----------------------------------"
           WScript.Echo "Found version: " & strDisplayName
           WScript.Echo "Found at: HKEY_LOCAL_MACHINE\" & strRegistryPath & strUninstallKey
           
           'UninstallString might be a REG_EXPAND_SZ but GetStringValue should retrieve what we want.
           objRegistry.GetStringValue &H80000002, strRegistryPath & strUninstallKey, "UninstallString", strUninstallString
       
           'Just in case GetStringValue doesn't retrieve what we want.
           If Err.Number <> 0 Then
               Wscript.Echo vbCrLf & "----------------------------------"
               WScript.Echo "Could not retrieve uninstall information for " & strDisplayName & "!"
               WScript.Echo "Error Number: " & Err.Number
               WScript.Echo "Error Description: " & Err.Description
               Wscript.Echo "----------------------------------"
               strUninstallString = ""
               Err.Clear
           End If
           
           'Slightly convoluted logic that determines if we're keeping or removing specific versions.
           For Each strVersion In aryVersions
               If (bolKeepJava) Then
                   If (Instr(1, strDisplayName, strVersion, 1) > 0) Then
                       strUninstallString = ""
                   End If
               Else
                   If (Instr(1, strDisplayName, strVersion, 1) < 1) Then
                       strUninstallString = ""
                   End If
               End If
           Next
           
           If (strUninstallString <> "") Then
               'Look for very old JRE 1.1, 1.2.x, or 1.3.0 to 1.3.0_04 and 1.3.1 to 1.3.1_04 InstallShield installs.
               If (Instr(1, strUninstallKey, "JRE 1", 1)) Then
                   strUninstallString = Replace(strUninstallString, "-f", "-a -x -y -f")
               'Look for 1.3.0_05 and 1.3.1_05 to 1.3.1_20 InstallShield based installs.
               ElseIf (Instr(1, strUninstallString, "-uninst", 1)) Then
                   strUninstallString = ""
                   WScript.Echo "Java versions 1.3.0_05 and 1.3.1_05 through 1.3.1_20 cannot be silently uninstalled."
               'Look for a 1.4.0 to 1.4.1_07 InstallShield installation.
               ElseIf (Instr(1, strUninstallString, "Anytext", 1)) Then
                   'Create ISS script for this install and fix the uninstall string.
                   If (CreateISSFile(strUninstallKey, objWSHShell.ExpandEnvironmentStrings("%TEMP%"))) Then
                       strUninstallString = Replace(strUninstallString, "Anytext", "/s /SMS /w /f1""" & objWSHShell.ExpandEnvironmentStrings("%TEMP%") _
                           & "\" & strUninstallKey & ".iss""")
                       'Check and add the logfile to the uninstaller string.
                       If (strLogFilePath <> "") Then
                           strUninstallString = strUninstallString & " /f2""" & strLogFilePath & strDisplayName & "_Uninstall.txt"""
                       End If
                   Else
                       strUninstallString = ""
                   End If
               'Look for 1.4.2 and up MSI based InstallShield installs.
               ElseIf (Instr(1, strUninstallString, "msiexec.exe", 1)) Then
                   'Create MSIEXEC uninstall string.
                   strUninstallString = "MSIEXEC.EXE /X " & strUninstallKey & " /qn /norestart"
                   'Check and add the logfile to the uninstaller string.
                   If (strLogFilePath <> "") Then
                       strUninstallString = strUninstallString & " /l*v """ & strLogFilePath & strDisplayName & "_Uninstall.txt"""
                   End If
               Else
                   strUninstallString = ""
               End If
           Else
               strUninstallString = ""
           End If
           
           WScript.Echo "Uninstall string: " & strUninstallString
           
           If (strUninstallString = "") Then
               WScript.Echo strDisplayName & " was not uninstalled."
           Else
               'Run the uninstaller.
               intUninstallReturnCode = objWSHShell.Run(strUninstallString, 0, true)
               WScript.Echo "Uninstall return code was: " & intUninstallReturnCode & "."
           End If
           
           WScript.Echo "----------------------------------"
           
       End If
   
   Next
   
   'Resume normal quit on error behavior.
   On Error GoTo 0
   
End Function

Function CreateISSFile(strUninstallKey, strTempPath)
   On Error Resume Next
   
   Dim objFileSystem, objUninstallScript
   
   Set objFileSystem  = CreateObject("Scripting.FileSystemObject")
   
   'Create InstallShield ISS script file for the uninstallation.
   Set objUninstallScript = objFileSystem.OpenTextFile(strTempPath & "\" & strUninstallKey & ".iss", 2, True)
   
   If (Err.Number <> 0) Then
       WScript.Echo "Could not create uninstall file at " & strTempPath & "\" & strUninstallKey & ".iss!"
       WScript.Echo "Error Number: " & Err.Number
       WScript.Echo "Error Description: " & Err.Description
       Err.Clear
       CreateISSFile = 0
   End If
   
   'One ugly write statement to cut down on the ammount of error checking that has to be done.
   'That SharedFile=YesToAll creates problems with multiple versions of 1.4.0 to 1.4.1_07 installed.
   objUninstallScript.Write "[InstallShield Silent]" & vbCrLf & "Version=v6.00.000" & vbCrLf & "File=Response File" & vbCrLf & "[File Transfer]" & _
       vbCrLf & "OverwrittenReadOnly=NoToAll" & vbCrLf & "[" & strUninstallKey & "-DlgOrder]" & vbCrLf & "Dlg0=" & strUninstallKey & "-SprintfBox-0" & _
       vbCrLf & "Count=2" & vbCrLf & "Dlg1=" & strUninstallKey & "-File Transfer" & vbCrLf & "[" & strUninstallKey & "-SprintfBox-0]" & vbCrLf & "Result=1" & _
       vbCrLf & "[Application]" & vbCrLf & "Name=Java 2 Runtime Environment, SE v1.4.0" & vbCrLf & "Version=1.4.0" & vbCrLf & "Company=JavaSoft" & _
       vbCrLf & "Lang=0009" &     vbCrLf & "[" & strUninstallKey & "-File Transfer]" & vbCrLf & "SharedFile=NoToAll"
       
   If (Err.Number <> 0) Then
       WScript.Echo "Could not create uninstall file at " & strTempPath & "\" & strUninstallKey & ".iss!"
       WScript.Echo "Error Number: " & Err.Number
       WScript.Echo "Error Description: " & Err.Description    
       Err.Clear
       CreateISSFile = 0
   End If
       
   objUninstallScript.Close
   
   If (Err.Number <> 0) Then
       WScript.Echo "Could not create uninstall file at " & strTempPath & "\" & strUninstallKey & ".iss!"
       WScript.Echo "Error Number: " & Err.Number
       WScript.Echo "Error Description: " & Err.Description
       Err.Clear
       CreateISSFile = 0
   End If
   
       
   CreateISSFile = 1
   
End Function

Function PrintHelp()
   'Just prints out the help when run with /help /? or no arguments.
   WScript.Echo vbCrLf & "Java Runtime Environment Removal Script v3.0" & vbCrLf
   WScript.Echo "Removes Java runtimes based on command line parameters." & vbCrLf & "Default parameters removes all Java versions without creating logs."
   WScript.Echo "Does not uninstall Java versions 1.3.0_05 and 1.3.1_05 through 1.3.1_20." & vbCrLf & "They do not uninstall silently." & vbCrLf
   WScript.Echo "Command line switches:" & vbCrLf
   WScript.Echo "/keeponly" & vbTab & vbTab & "Script keeps only versions specified." & vbCrLf & vbTab & vbTab & vbTab & "If no versions are specified no versions are kept." & vbCrLf
   WScript.Echo "/removeonly" & vbTab & vbTab & "Script removes only versions specified." & vbCrLf & vbTab & vbTab & vbTab & "If no versions are specified no versions are removed." & vbCrLf
   WScript.Echo "/versions:" & vbTab & vbTab & "Specifies verions to act on." & vbCrLf & vbTab & vbTab & vbTab & "Versions are seperated by semicolons." & vbCrLf & vbTab & vbTab & vbTab & _
               "By default specified versions are kept." & vbCrLf & vbTab & vbTab & vbTab & "MUST MATCH THE DISPLAY NAME IN ADD/REMOVE PROGRAMS" & vbCrLf
   WScript.Echo "/versionsx86onx64:" & vbTab & "Specifies x86 runtime versions to keep on a x64 system." & vbCrLf & vbTab & vbTab & vbTab & _
               "Versions are seperated by semicolon." & vbCrLf & vbTab & vbTab & vbTab & _
               "If no x86 versions are specified script uses versions"  & vbCrLf & vbTab & vbTab & vbTab & "specified by /versions for both x64 and x86 runtimes." _
                & vbCrLf & vbTab & vbTab & vbTab & "MUST MATCH THE DISPLAY NAME IN ADD/REMOVE PROGRAMS" & vbCrLf
   Wscript.Echo "/logfilepath:" & vbTab & vbTab & "Sets path for uninstall log file from Java runtimes." & vbCrLf & vbTab & vbTab & vbTab & _
               "If path does not exist uninstallers will fail." & vbCrLf
   WScript.Echo "Examples:" & vbCrLf
   WScript.Echo "cscript /nologo JavaUninstallScript.vbs /keeponly /versions:""Java(TM) 6 Update 24;J2SE Runtime Environment 5.0 Update 16"" /logfilepath:""C:\Temp"""
   WScript.Echo "Removes all Java Runtimes found except Java 6 Update 24 and J2SE 5 Update 16 and places the uninstall logs in C:\Temp." & vbCrLf
   WScript.Echo "cscript /nologo JavaUninstallScript.vbs /keeponly /versions:""Java(TM) 6 Update 24"" /versionsx86onx64:""J2SE Runtime Environment 5.0 Update 16"" /logfilepath:""C:\Temp"""
   WScript.Echo "Removes all Java Runtimes found except x64 Java 6 Update 24 and x86 J2SE 5 Update 16 on a x64 system and places the uninstall logs in C:\Temp." & vbCrLf
   WScript.Echo "cscript /nologo JavaUninstallScript.vbs /keeponly"
   WScript.Echo "Removes all Java Runtimes without creating logs." & vbCrLf
   WScript.Echo "cscript /nologo JavaUninstallScript.vbs /removeonly"
   WScript.Echo "Keeps all Java Runtimes. Only useful for making a list of installed runtimes." & vbCrLf
End Function