Option Explicit

'==========================================================
' LANG : VBScript
' NAME : sydi-MOM.vbs
' AUTHOR : Garth Jones (Garth@enhansoft.com)
' Based on SYDI-Server wrtten Patrick Ogenstad (patrick.ogenstad@netsafe.se)
' VERSION : 1.0
' DATE : 2006-09-05
' Description : Creates a basic documentation for  
' Microsoft Opetation Manager 2005, which you can use as a starting point.
'
' COMMENTS : You are supposed to change the text appearing inside
' brackets. 
'
' UPDATES : http://www.enhansoft.com/index_files/FreeTools.htm
'
' Running the script:
' You have to have  Word installed on the computer you are running
' the script from. I would recommend running the script with cscript
' instead of wscript.
' For Options: cscript.exe sydi-SMS.vbs
' Feedback: Please send feedback to Garth@enhansoft.com
'
' LICENSE :
' Copyright (c) 2006, Garth Jones
' All rights reserved.
'
' Redistribution and use in source and binary forms, with or without
' modification, are permitted provided that the following conditions are met:
'
'  * Redistributions of source code must retain the above copyright notice,
'    this list of conditions and the following disclaimer.
'  * Redistributions in binary form must reproduce the above copyright notice,
'    this list of conditions and the following disclaimer in the documentation
'    and/or other materials provided with the distribution.
'  * Neither the name SYDI nor the names of its contributors may be used
'    to endorse or promote products derived from this software without
'    specific prior written permission.
'
' THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
' IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
' ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
' LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
' CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
' SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
' INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
' CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
' ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
' POSSIBILITY OF SUCH DAMAGE.
'==========================================================


' Settings
Dim strDocumentAuthor, strComputer

' Who Authored the document
strDocumentAuthor = "Garth Jones"

' Script version
Dim strScriptVersion
strScriptVersion = "1.0"

' Fonts to use in document
Dim strFontBodyText, strFontHeading1, strFontHeading2, strFontHeading3, strFontHeading4, strFontTitle, strFontTOC1, strFontTOC2, strFontTOC3
Dim strFontHeader, strFontFooter
strFontBodyText = "Arial"
strFontHeading1 = "Trebuchet MS"
strFontHeading2 = "Trebuchet MS"
strFontHeading3 = "Trebuchet MS"
strFontHeading4 = "Trebuchet MS"
strFontTitle = "Trebuchet MS"
strFontTOC1 = "Trebuchet MS"
strFontTOC2 = "Trebuchet MS"
strFontTOC3 = "Trebuchet MS"
strFontHeader = "Arial"
strFontFooter = "Arial"
nBaseFontSize = 12

' Username and Password
Dim strUserName, strPassword
' Other
Dim bInvalidArgument, bDisplayHelp, bAlternateCredentials, bCheckVersion
' Word
Dim bShowWord, bWordExtras, bUseDOTFile, bSaveFile, bUseSpecificTable
Dim strDOTFile, strWordTable
' Export Options
Dim strExportFormat, strSaveFile
' XML Options
Dim strStylesheet, strXSLFreeText

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20


' Variables for the Win32_ComputerSystem class
Dim strComputerSystem_Name, strComputerSystem_TotalPhysicalMemory, strComputerSystem_Domain, nComputerSystem_DomainRole
Dim strTotalPhysicalMemoryMB, strDomainType, strComputerRole

' Variables for the Win32_OperatingSystems Class
Dim strOperatingSystem_InstallDate, strOperatingSystem_Caption, strOperatingSystem_ServicePack, strOperatingSystem_WindowsDirectory
Dim strOperatingSystem_LanguageCode, arrOperatingSystem_Name


' Variables for the MSFT_MicrosoftOperationsManager
Dim MOMMSDateInstalled, MOMMSDescription, MOMMSName, MOMMSVersion 

' Variables for the MSFT_Computer
dim objMOMCom


' Variables for the MSFT_ComputerGroup
dim objMOMComG


' Variables to handle different versions of Windows
Dim nOperatingSystemLevel


' Objects for WMI and Word
Dim objWMIService, colItems, objItem, oReg
Dim oWord, oListTemplate

' Variables for System Roles
Dim bRoleSMS, bRoleMP, bRoleCAP, bRoleSQL, bRoleRP, bRoleDP, objDbrSystemRoles


' Variables for routines
Dim errGatherWMIInformation, errGatherRegInformation, errWin32_Product
Dim bAllowErrors, bHasSMS

Dim bRegDomainSuffix, bRegLastUser,bDoRegistryCheck, debugmode

debugmode = FALSE

'SMS WMI Prov
Dim SMSProv

' Constants
Const adVarChar = 200
Const MaxCharacters = 255

Dim nBaseFontSize


bShowWord = True

'==========================================================
'==========================================================
' Main Body

If LCase (Right (WScript.FullName, 11)) <> "cscript.exe" Then
    MsgBox "This script should be run from a command line (eg ""cscript.exe sydi-MOM.vbs"")", vbCritical, "Error"
    WScript.Quit
End If


' Get Options from user
GetOptions



If (bInvalidArgument) Then
	WScript.Echo "Invalid Arguments" & VbCrLf
	bDisplayHelp = True
End If

If (bDisplayHelp) Then
	DisplayHelp
Else
	If (bCheckVersion) Then
		CheckVersion
	End If
	If (strComputer = "") Then
		strComputer = InputBox("What Computer do you want to document (default=localhost)","Select Target",".")
	End If
	If (strComputer <> "") Then
		' Run the GatherWMIInformation() function and return the status
		' to errGatherInformation, if the function fails then the
		' rest is skipped. The same applies to GatherRegInformation
		' if it is successful we place the information in a
		' new word document
		GetWMIProviderList
		if (bHasSMS) then
			GetSMSProvider
		end if

		errGatherWMIInformation = GatherWMIInformation()
		If (errGatherWMIInformation) Then
			If (bDoRegistryCheck) Then
				errGatherRegInformation = GatherRegInformation
			End If
			GetWMIProviderList
'			if (bHasSMS) then
'				GetSMSProvider
'			end if
		End If

'		If (bHasMicrosoftIISv2) Then ' Does the system have the WMI IIS Provider
'			GatherIISInformation
'		End If

		SystemRolesSet
		
		If (errGatherWMIInformation) Then
			Select Case strExportFormat
				Case "word"
					PopulateWordfile
				Case "xml"
					PopulateXMLFile
			End Select
		End If
	End If
End If

'==========================================================

Function GatherWMIInformation

	If (bAllowErrors) Then
		On Error Resume Next
	End If


	If (bAlternateCredentials) Then
		Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objSWbemLocator.ConnectServer(strComputer,"root\cimv2",strUserName,strPassword)
	Else
		Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
	End If
	If (Err <> 0) Then
	    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strComputer & ")"
	    Err.Clear
	    GatherWMIInformation = False
	    Exit Function
	End If


	'--------------------------------------------------------------------------------
	'OS
	'--------------------------------------------------------------------------------

	ReportProgress " Gathering OS information"
	Set colItems = objWMIService.ExecQuery("Select Name, CSDVersion, InstallDate, OSLanguage, Version, WindowsDirectory from Win32_OperatingSystem",,48)
	For Each objItem in colItems
		strOperatingSystem_InstallDate = objItem.InstallDate
		arrOperatingSystem_Name = Split(objItem.Name,"|")
		strOperatingSystem_Caption = arrOperatingSystem_Name(0)
		strOperatingSystem_ServicePack = objItem.CSDVersion
		strOperatingSystem_LanguageCode = Clng(objItem.OSLanguage)
		strOperatingSystem_LanguageCode = Hex(strOperatingSystem_LanguageCode)
		nOperatingSystemLevel = objItem.Version
		strOperatingSystem_WindowsDirectory = objItem.WindowsDirectory
	Next
	nOperatingSystemLevel = Mid(nOperatingSystemLevel,1,1) & Mid(nOperatingSystemLevel,3,1) ' 50 for Win2k 51 for XP

	'--------------------------------------------------------------------------------
	'Computer System
	'--------------------------------------------------------------------------------

	ReportProgress " Gathering computer system information"
	Set colItems = objWMIService.ExecQuery("Select Domain, DomainRole, Name, TotalPhysicalMemory from Win32_ComputerSystem",,48)
	For Each objItem in colItems
		strComputerSystem_Domain = objItem.Domain
		nComputerSystem_DomainRole = objItem.DomainRole
		strComputerSystem_Name = objItem.Name
		strComputerSystem_TotalPhysicalMemory = objItem.TotalPhysicalMemory
		strTotalPhysicalMemoryMB = Round(strComputerSystem_TotalPhysicalMemory / 1024 / 1024)
		Select Case nComputerSystem_DomainRole
			Case 0 
	            strComputerRole = "Standalone Workstation" : strDomainType = "workgroup"
	        Case 1        
	            strComputerRole = "Member Workstation" : strDomainType = "domain"
	        Case 2
	            strComputerRole = "Standalone Server" : strDomainType = "workgroup"
	        Case 3
	            strComputerRole = "Member Server" : strDomainType = "domain"
	        Case 4
	        	bWMILocalAccounts = False
	        	bWMILocalGroups = False
	            strComputerRole = "Domain Controller" : strDomainType = "domain"
	            bRoleDC = True
	        Case 5
	        	bWMILocalAccounts = False
	        	bWMILocalGroups = False
	            strComputerRole = "Domain Controller (PDC Emulator)" : strDomainType = "domain"
	            bRoleDC = True
		End Select
	Next
	If (bAlternateCredentials) Then
		Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
'		Set objWMIService = objSWbemLocator.ConnectServer(strComputer,& "root\MOM",strUserName,strPassword)
	Else
		Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\MOM")
	End If
	If (Err <> 0) Then
	    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strComputer & ")"
	    Err.Clear
	    GatherWMIInformation = False
	    Exit Function
	End If

	'--------------------------------------------------------------------------------
	'MOM Management Server
	'--------------------------------------------------------------------------------

	ReportProgress " MOM Management Server"
	Set colItems = objWMIService.ExecQuery("SELECT * FROM MSFT_MicrosoftOperationsManager", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
	For Each objItem In colItems
		MOMMSDateInstalled = cstr( WMIDateStringToDate(objItem.DateInstalled) )
		MOMMSDescription = objItem.Description
		MOMMSName = objItem.Name
		MOMMSVersion = objItem.Version
	next

	'--------------------------------------------------------------------------------
	'MOM Management Server
	'--------------------------------------------------------------------------------
	ReportProgress " MOM Managed Computer"
	Set colItems = objWMIService.ExecQuery("SELECT * FROM MSFT_Computer", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
	set objMOMCom = createobject("ADOR.Recordset")
	objMOMCom.fields.append "Description", advarchar, MaxCharacters
	objMOMCom.fields.append "DNSName", advarchar, MaxCharacters
	objMOMCom.fields.append "Domain", advarchar, MaxCharacters
	objMOMCom.fields.append "GUID", advarchar, MaxCharacters
	objMOMCom.fields.append "IsAgent", advarchar, MaxCharacters
	objMOMCom.fields.append "IsConsolidator", advarchar, MaxCharacters
	objMOMCom.fields.append "LastModifiedBy", advarchar, MaxCharacters
	objMOMCom.fields.append "Name", advarchar, MaxCharacters
	objMOMCom.fields.append "TimeAdded", advarchar, MaxCharacters
	objMOMCom.fields.append "TimeLastContacted", advarchar, MaxCharacters
	objMOMCom.fields.append "TimeLastModified", advarchar, MaxCharacters
	objMOMCom.fields.append "Type", advarchar, MaxCharacters
	objMOMCom.open
	
	For Each objItem In colItems
		objMOMCom.addnew
		objMOMCom("Description") = objItem.Description
		objMOMCom("DNSName") = objItem.DNSName
		objMOMCom("Domain") = objItem.Domain
		objMOMCom("GUID") = objItem.GUID
		objMOMCom("IsAgent") = objItem.IsAgent
		objMOMCom("IsConsolidator") = objItem.IsConsolidator
		objMOMCom("LastModifiedBy") = objItem.LastModifiedBy
		objMOMCom("Name") = objItem.Name
		objMOMCom("TimeAdded") = WMIDateStringToDate(objItem.TimeAdded)
		objMOMCom("TimeLastContacted") = WMIDateStringToDate(objItem.TimeLastContacted)
		objMOMCom("TimeLastModified") = WMIDateStringToDate(objItem.TimeLastModified)
		objMOMCom("Type") = objItem.Type
		objMOMCom.update
	next
	objMOMCom.sort = "Name"

	'--------------------------------------------------------------------------------
	'MOM Computer Group
	'--------------------------------------------------------------------------------
	ReportProgress " MOM Computer Groups"
	Set colItems = objWMIService.ExecQuery("SELECT * FROM MSFT_ComputerGroup", "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
	set objMOMComG = createobject("ADOR.Recordset")
	objMOMComG.fields.append "Description", advarchar, MaxCharacters
	objMOMComG.fields.append "GUID", advarchar, MaxCharacters
	objMOMComG.fields.append "IsEnabled", advarchar, MaxCharacters
	objMOMComG.fields.append "GUID", advarchar, MaxCharacters
	objMOMComG.fields.append "Name", advarchar, MaxCharacters
	objMOMComG.fields.append "Type", advarchar, MaxCharacters
	objMOMComG.open
	
	For Each objItem In colItems
		objMOMComG.addnew
		objMOMComG("Description") = objItem.Description
		objMOMComG("GUID") = objItem.GUID
		objMOMComG("IsEnabled") = objItem.IsAgent
		objMOMComG("Name") = objItem.Name
		objMOMComG("Type") = objItem.Type
		objMOMComG.update
	next
	objMOMComG.sort = "Name"



	GatherWMIInformation = True
end function 'GatherWMIInformation

Sub PopulateWordfile()

	If (bAllowErrors) Then
		On Error Resume Next
	End If
	' WdListNumberStyle
	Const wdListNumberStyleArabic = 0
	Const wdListNumberStyleUppercaseRoman = 1
	Const wdListNumberStyleLowercaseRoman = 2
	Const wdListNumberStyleUppercaseLetter = 3
	Const wdListNumberStyleLowercaseLetter = 4
	Const wdListNumberStyleOrdinal = 5
	Const wdListNumberStyleCardinalText = 6
	Const wdListNumberStyleOrdinalText = 7
	Const wdListNumberStyleArabicLZ = 22
	Const wdListNumberStyleBullet = 23
	Const wdListNumberStyleLegal = 253
	Const wdListNumberStyleLegalLZ = 254
	Const wdListNumberStyleNone = 255
	
	' WdListGalleryType
	Const wdBulletGallery = 1
	Const wdNumberGallery = 2
	Const wdOutlineNumberGallery = 3
	' WdBreakType
	Const wdPageBreak = 7
	' WdBuiltInProperty
	Const wdPropertyAuthor = 3
	Const wdPropertyComments = 5
	' WdBuiltInStyle
	Const wdStyleBodyText = -67
	Const wdStyleFooter = -33
	Const wdStyleHeader = -32
	Const wdStyleHeading1 = -2
	Const wdStyleHeading2 = -3
	Const wdStyleHeading3 = -4
	Const wdStyleHeading4 = -5
	Const wdStyleTitle = -63
	Const wdStyleTOC1 = -20
	Const wdStyleTOC2 = -21
	Const wdStyleTOC3 = -22
	' WdFieldType
	'Const wdFieldEmpty = -1
	Const wdFieldNumPages = 26
	Const wdFieldPage = 33
	' WdParagraphAlignment
	Const wdAlignParagraphRight = 2
	' WdSeekView
	Const wdSeekMainDocument = 0
	Const wdSeekCurrentPageHeader = 9
	Const wdSeekCurrentPageFooter = 10
	' Page Viewing
	Const wdPaneNone = 0
	Const wdPrintView = 3

	
	ReportProgress VbCrLf & "Start subroutine: PopulateWordfile()"
	Set oWord = CreateObject("Word.Application")
	If (Err <> 0) Then
	    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strComputer & ")"
	    ReportProgress " Could not open Microsoft Word, verify that it is correctly installed on the computer you are scanning from."
	    Err.Clear
	    Exit Sub
	End If

	'oWord.Activate
	
	If (bUseDOTFile) Then
		oWord.Documents.Add strDOTFile
		If (Err <> 0) Then
		    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strDOTFile & ")"
		    ReportProgress " Unable to open the template file " & strDOTFile
		    ReportProgress " Did you use the correct path?"
		    Err.Clear
		    Exit Sub
		End If
	Else
		oWord.Documents.Add
	End If
	oWord.Application.Visible = bShowWord
	ReportProgress " Opening Empty document"
	Set oListTemplate = oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1)
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(1).Numberformat = "%1."
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(1).NumberStyle = wdListNumberStyleArabic
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(2).Numberformat = "%1.%2."
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(2).NumberStyle = wdListNumberStyleArabic
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(3).Numberformat = "%1.%2.%3."
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(3).NumberStyle = wdListNumberStyleArabic
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(4).Numberformat = "%1.%2.%3.%4."
	oWord.ListGalleries(wdOutlineNumberGallery).ListTemplates(1).listlevels(4).NumberStyle = wdListNumberStyleArabic

	If Not (bUseDOTFile) Then
		oWord.ActiveDocument.Styles(wdStyleTOC1).Font.Bold = True
		oWord.ActiveDocument.Styles(wdStyleBodyText).Font.Name = strFontBodyText
		oWord.ActiveDocument.Styles(wdStyleBodyText).Font.Size = nBaseFontSize
		oWord.ActiveDocument.Styles(wdStyleHeading1).Font.Name = strFontHeading1
		oWord.ActiveDocument.Styles(wdStyleHeading1).Font.Size = (nBaseFontSize + 4)
		oWord.ActiveDocument.Styles(wdStyleHeading2).Font.Name = strFontHeading2
		oWord.ActiveDocument.Styles(wdStyleHeading2).Font.Size = (nBaseFontSize + 2)
		oWord.ActiveDocument.Styles(wdStyleHeading3).Font.Name = strFontHeading3
		oWord.ActiveDocument.Styles(wdStyleHeading3).Font.Size = (nBaseFontSize + 1)
		oWord.ActiveDocument.Styles(wdStyleHeading4).Font.Name = strFontHeading4
		oWord.ActiveDocument.Styles(wdStyleHeading4).Font.Size = nBaseFontSize
		oWord.ActiveDocument.Styles(wdStyleTitle).Font.Name = strFontTitle
		oWord.ActiveDocument.Styles(wdStyleTitle).Font.Size = (nBaseFontSize + 4)
		oWord.ActiveDocument.Styles(wdStyleTOC1).Font.Name = strFontTOC1
		oWord.ActiveDocument.Styles(wdStyleTOC1).Font.Size = nBaseFontSize
		oWord.ActiveDocument.Styles(wdStyleTOC2).Font.Name = strFontTOC2
		oWord.ActiveDocument.Styles(wdStyleTOC2).Font.Size = nBaseFontSize
		oWord.ActiveDocument.Styles(wdStyleTOC3).Font.Name = strFontTOC3
		oWord.ActiveDocument.Styles(wdStyleTOC3).Font.Size = nBaseFontSize
		oWord.ActiveDocument.Styles(wdStyleHeader).Font.Name = strFontHeader
		oWord.ActiveDocument.Styles(wdStyleHeader).Font.Size = (nBaseFontSize - 1)
		oWord.ActiveDocument.Styles(wdStyleFooter).Font.Name = strFontFooter
		oWord.ActiveDocument.Styles(wdStyleFooter).Font.Size = (nBaseFontSize - 1)
		ReportProgress " Setting styles"	
	End If

	oWord.Selection.Style = wdStyleTitle
	oWord.Selection.TypeText "Basic documentation For " & strComputerSystem_Name & VbCrLf & VbCrLf

	If (strDocumentAuthor = "") Then
		strDocumentAuthor = oWord.ActiveDocument.BuiltInDocumentProperties(wdPropertyAuthor).Value
	End If
	oWord.Selection.Style = wdStyleBodyText
	oWord.Selection.TypeText "Document versions:" & vbCrLf & "Version 1.0" & vbTab & Date & vbTab & strDocumentAuthor & vbTab & "First Draft" & vbCrLf & vbCrLf
	
	oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText "SUMMARY" & vbCrLf
	oWord.Selection.Font.Bold = False
	
	oWord.Selection.Style = wdStyleBodyText
	If (bWordExtras) Then 
		oWord.Selection.TypeText "[Introduce the system in a short sentence]. "
	End If
	oWord.Selection.TypeText "The system is running " & strOperatingSystem_Caption & " " & strOperatingSystem_ServicePack & VbCrLf

	If (bWordExtras) Then 
		oWord.Selection.TypeText "System Owner: "
		oWord.Selection.TypeText "[provide name and title]" & VbCrLf
	End If

	If (bRegDomainSuffix) Then
		oWord.Selection.TypeText "FQDN: " &  LCase(strComputerSystem_Name) & "." & strPrimaryDomain & VbCrLf
	End If
	oWord.Selection.TypeText "NetBIOS: " & strComputerSystem_Name & VbCrLf
	oWord.Selection.TypeText "Roles: "

	i = 0
	If Not (objDbrSystemRoles.Bof) Then
		objDbrSystemRoles.MoveFirst
	End If
	Do Until objDbrSystemRoles.EOF
		If (i = 0) Then
			oWord.Selection.TypeText Cstr(objDbrSystemRoles.Fields.Item("Role"))
		Else
			oWord.Selection.TypeText ", " & Cstr(objDbrSystemRoles.Fields.Item("Role"))
		End If
		i = i + 1
		objDbrSystemRoles.MoveNext
	Loop
	If (i = 0) Then
		oWord.Selection.TypeText "[provide the roles of this system]" & vbCrLf
	Else
		oWord.Selection.TypeText vbCrLf
	End If
	If (bWordExtras) Then 
		oWord.Selection.TypeText "Physical location: "
		oWord.Selection.TypeText "[provide info: Floor 3, Street 3, Stockholm]" & vbCrLf
		oWord.Selection.TypeText "Logical location: " 
		oWord.Selection.TypeText "[provide info: Server VLAN 2]" & VbCrLf
	End If

	oWord.Selection.TypeText "Identifying Number: " & strComputerSystemProduct_IdentifyingNumber & VbCrLf 
	If (bWordExtras) Then 
		oWord.Selection.TypeText "Shipping date: "  
		oWord.Selection.TypeText "[provide shipping date]" & VbCrLf
		oWord.Selection.TypeText "Support contract: "  
		oWord.Selection.TypeText "[provide hardware service level purchased for this server]" & VbCrLf
		oWord.Selection.TypeText "Maintenance and changes to this documentation are recorded in "  
		oWord.Selection.TypeText "[reference to log file/system]." & VbCrLf
		oWord.Selection.TypeText "Continuity and disaster recovery are covered in "  
		oWord.Selection.TypeText "[reference to continuity plan]" & VbCrLf
	End If		

	
	ReportProgress " Writing summary"
	oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText vbCrLf & "TABLE OF CONTENTS" & vbCrLf
	oWord.Selection.Font.Bold = False

	oWord.ActiveDocument.TablesOfContents.Add oWord.Selection.Range, False, 2, 3, , , , ,oWord.ActiveDocument.Styles(wdStyleHeading1)& ";1", True
	
	
	ReportProgress " Inserting Table Of Contents"
	oWord.Selection.TypeText vbCrLf
	oWord.Selection.InsertBreak wdPageBreak

	'--------------------------------------------------------------------------------
	'Chapter 1 - System Information
	'--------------------------------------------------------------------------------
	If (bWordExtras) Then 
		ReportProgress " Writing System Information"
		WriteHeader 1,"System Information"
		oWord.Selection.Style = wdStyleBodyText
		oWord.Selection.TypeText "[Enter information about your server, what the system means to your organization, the purpose of this document etc.]" & vbCrLf
	End If
	oWord.Selection.TypeText VbCrLf

	'--------------------------------------------------------------------------------
	'Chapter 2 - Management Server Information
	'--------------------------------------------------------------------------------
	ReportProgress " Writing MOM Management Server"
	WriteHeader 1,"MOM Management Server"
	WriteHeader 2,"Basic Management Server information"
	oWord.Selection.Style = wdStyleBodyText
	oWord.Selection.TypeText VbCrLf
	oWord.Selection.TypeText "Management Server Name: "& cstr(MOMMSName) & vbCrLf
	oWord.Selection.TypeText "Description: "& cstr(MOMMSDescription) & vbCrLf
	oWord.Selection.TypeText "Build Number: "& cstr(MOMMSVersion) & vbCrLf
	oWord.Selection.TypeText "Date Installed: "& cstr(MOMMSDateInstalled) & vbCrLf


	'--------------------------------------------------------------------------------
	'Chapter 3 - Managed Computer
	'--------------------------------------------------------------------------------
	ReportProgress " Writing Computer Info"
	WriteHeader 1,"Managed Computer"
	WriteHeader 2,"List of Computers"
	oWord.Selection.Style = wdStyleBodyText
	oWord.Selection.TypeText VbCrLf
	oWord.Selection.Font.Bold = False

	oWord.ActiveDocument.Tables.Add oWord.Selection.Range, objMOMCom.Recordcount + 1, 3
		oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText "Name" : oWord.Selection.MoveRight
		oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText "Domain" : oWord.Selection.MoveRight
		oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText "Description" : oWord.Selection.MoveRight
	oWord.Selection.Font.Bold = False

	If Not (objMOMCom.Bof) Then
		objMOMCom.Movefirst
	End If			

	Do Until objMOMCom.EOF
		oWord.Selection.TypeText cstr( objMOMCom("Name") ) : oWord.Selection.MoveRight
		oWord.Selection.TypeText cstr( objMOMCom("Domain") ) : oWord.Selection.MoveRight
		oWord.Selection.TypeText cstr( objMOMCom("Description") ) : oWord.Selection.MoveRight
		objMOMCom.MoveNext
	Loop

	oWord.Selection.TypeText VbCrLf


	'--------------------------------------------------------------------------------
	'Chapter 3 - Managed Computer Group
	'--------------------------------------------------------------------------------
	ReportProgress " Writing Computer Group"
	WriteHeader 1,"Computer Group"
	WriteHeader 2,"List of Computers Group"
	oWord.Selection.Style = wdStyleBodyText
	oWord.Selection.TypeText VbCrLf
	oWord.Selection.Font.Bold = False

	oWord.ActiveDocument.Tables.Add oWord.Selection.Range, objMOMComG.Recordcount + 1, 2
		oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText "Name" : oWord.Selection.MoveRight
		oWord.Selection.Font.Bold = True
	oWord.Selection.TypeText "Description" : oWord.Selection.MoveRight
	oWord.Selection.Font.Bold = False

	If Not (objMOMComG.Bof) Then
		objMOMComG.Movefirst
	End If			

	Do Until objMOMComG.EOF
		oWord.Selection.TypeText cstr( objMOMComG("Name") ) : oWord.Selection.MoveRight
		oWord.Selection.TypeText cstr( objMOMComG("Description") ) : oWord.Selection.MoveRight
		objMOMComG.MoveNext
	Loop

	oWord.Selection.TypeText VbCrLf





	'--------------------------------------------------------------------------------
	'Close out tasks
	'--------------------------------------------------------------------------------


	If (bUseSpecificTable) Then
		For i = 1 To CInt(oWord.ActiveDocument.Tables.Count)
			oWord.ActiveDocument.Tables(i).Style = strWordTable
		Next
	
	End If
	
	If Not (bUseDOTFile) Then
		' Adding header and footer
		If oWord.ActiveWindow.View.SplitSpecial = wdPaneNone Then
			oWord.ActiveWindow.ActivePane.View.Type = wdPrintView
		Else
			oWord.ActiveWindow.View.Type = wdPrintView
		End If
		oWord.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
		oWord.Selection.TypeText "Basic documentation For " & strComputerSystem_Name
		oWord.ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageFooter
		oWord.Selection.ParagraphFormat.Alignment = wdAlignParagraphRight
		oWord.Selection.TypeText "Page ("
		oWord.Selection.Fields.Add oWord.Selection.Range, wdFieldPage
		oWord.Selection.TypeText "/"
		oWord.Selection.Fields.Add oWord.Selection.Range, wdFieldNumPages
		oWord.Selection.TypeText ")"
		oWord.ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
	End If
	
	' Update table of contents
	ReportProgress " Updating Tables Of Contents"	
	oWord.ActiveDocument.TablesOfContents.Item(1).Update
	
	oWord.ActiveDocument.BuiltInDocumentProperties(wdPropertyComments).Value = "Generated by SYDI-SMS " & strScriptVersion & " (http://www.Enhansoft.com)"
	
	If (bSaveFile) Then 
		ReportProgress " Saving Document"	
		oWord.ActiveDocument.SaveAs strSaveFile
		If (Err <> 0) Then
		    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strSaveFile & ")"
		    ReportProgress " Would not save to " & strSaveFile
		    ReportProgress " Did you specify a path?"
		    Err.Clear
		    Exit Sub
		End If
	End If
	
	If (bShowWord = False And bSaveFile = True) Then
		ReportProgress " Document Saved"
		oWord.Application.Quit
		Set oWord = Nothing
		ReportProgress "End subroutine: PopulateWordfile()"
	Else
		oWord.Application.Visible = True
		ReportProgress "End subroutine: PopulateWordfile()"
	End If
	
	Set oListTemplate = Nothing
	Set oWord = Nothing

End Sub ' PopulateWordfile

Sub ReportProgress(strMessage)
	WScript.Echo strMessage
End Sub ' ReportProgress

Sub GetOptions()
	Dim objArgs, nArgs
	' Default settings
'	bWMIBios = True
'	bWMIRegistry = True
'	bWMIApplications = True
'	bWMIPatches = True
'	bWMIEventLogFile = True
'	bWMIFileShares = True
'	bWMIIP4Routes = True
'	bWMILocalAccounts = True
'	bWMILocalGroups = True
'	bWMIServices = True
'	bWMIStartupCommands = True
'	bWMIPrinters = True
'	bWMIRunningProcesses = True
'	bWMIHardware = True
'	bHasTapeDrive = False
'	bRegDomainSuffix = True
'	bRegPrintSpoolLocation = True
'	bRegPrograms = True
'	bRegWindowsComponents = True
	bRegLastUser = True
	bDoRegistryCheck = True
	strComputer = ""
	bAlternateCredentials = False
	bInvalidArgument = False
	bDisplayHelp = False
	bShowWord = True
	bWordExtras = True 
	nBaseFontSize = 12
	bUseSpecificTable = False
	bUseDOTFile = False
'	bSaveFile = False
'	bCheckVersion = False
	strExportFormat = "word"
	strStylesheet = ""
	bAllowErrors = True
	Set objArgs = WScript.Arguments
	If (objArgs.Count > 0) Then
		For nArgs = 0 To objArgs.Count - 1
			SetOptions objArgs(nArgs)
		Next
	Else
		WScript.Echo "For help type: cscript.exe sydi-server.vbs -h"
	End If
	SystemRolesDefine
	If (bSaveFile = False And strExportFormat = "xml") Then
		bInvalidArgument = True
	End If
End Sub ' GetOptions

Sub WriteHeader(nHeaderLevel,strHeaderText)
	Const wdStyleHeading1 = -2
	Const wdStyleHeading2 = -3
	Const wdStyleHeading3 = -4
	Const wdStyleHeading4 = -5

	Select Case nHeaderLevel
		Case 1
			oWord.Selection.Style = wdStyleHeading1
		Case 2
			oWord.Selection.Style = wdStyleHeading2
		Case 3
			oWord.Selection.Style = wdStyleHeading3
		Case 4
			oWord.Selection.Style = wdStyleHeading4
	End Select
	oWord.Selection.Range.ListFormat.ApplyListTemplate oListTemplate, True
	oWord.Selection.TypeText strHeaderText & vbCrLf
End Sub ' WriteHeader

Sub SystemRolesDefine()
	bRoleSMS = TRUE
	bRoleMP = False
	bRoleCAP = False
	bRoleRP = False
	bRoleSQL = TRUE
	bRoleDP = TRUE
End Sub ' SystemRolesDefine


Sub SystemRolesSet()
	Set objDbrSystemRoles = CreateObject("ADOR.Recordset")
	objDbrSystemRoles.Fields.Append "Role", adVarChar, MaxCharacters
	objDbrSystemRoles.Open

	If (bRoleSMS) Then
		objDbrSystemRoles.AddNew
		objDbrSystemRoles("Role") = "Primary Site"
		objDbrSystemRoles.Update
	End If
	If (bRoleMP) Then
		objDbrSystemRoles.AddNew
		objDbrSystemRoles("Role") = "Management Point"
		objDbrSystemRoles.Update
	End If
	If (bRoleCAP) Then
		objDbrSystemRoles.AddNew
		objDbrSystemRoles("Role") = "Client Access Point"
		objDbrSystemRoles.Update
	End If
	If (bRoleRP) Then
		objDbrSystemRoles.AddNew
		objDbrSystemRoles("Role") = "Reporting Server"
		objDbrSystemRoles.Update
	End If
	If (bRoleSQL) Then
		objDbrSystemRoles.AddNew
		objDbrSystemRoles("Role") = "SQL"
		objDbrSystemRoles.Update
	End If
End Sub ' SystemRolesSet

Sub GetWMIProviderList
	If (bAllowErrors) Then
		On Error Resume Next
	End If
	Dim colNameSpaces
	ReportProgress vbCrlf & "Checking for Other WMI Providers"
	Dim objSWbemLocator
	If (bAlternateCredentials) Then
		Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objSWbemLocator.ConnectServer(strComputer,"root",strUserName,strPassword)
	Else
		Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root")
	End If
	If (Err <> 0) Then
	    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strComputer & ")"
	    Err.Clear
	    Exit Sub
	End If
	Set colNameSpaces = objWMIService.InstancesOf("__NAMESPACE")
	For Each objItem In colNameSpaces
		Select Case objItem.Name
			Case "MicrosoftIISv2"
				bHasMicrosoftIISv2 = True
				ReportProgress " Found MicrosoftIISv2 (Internet Information Services)"
			Case "SMS"
				bHasSMS = True
				ReportProgress " Found SMS"

		End Select
	Next	
End Sub ' GetWMIProviderList


Sub GetSMSProvider
	If (bAllowErrors) Then
		On Error Resume Next
	End If
	Dim colNameSpaces
	ReportProgress vbCrlf & "Checking SMS WMI Providers"
	Dim objSWbemLocator
	If (bAlternateCredentials) Then
		Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objWMIService = objSWbemLocator.ConnectServer(strComputer,"root",strUserName,strPassword)
	Else
		Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\SMS")
	End If
	If (Err <> 0) Then
	    ReportProgress Err.Number & " -- " &  Err.Description & " (" & strComputer & ")"
	    Err.Clear
	    Exit Sub
	End If
	Set colNameSpaces = objWMIService.InstancesOf("__NAMESPACE")
	For Each objItem In colNameSpaces
		if (instr(objitem.name,"site_") >0) then
			SMSProv = objitem.name
		end if
			
	Next	
	wscript.echo cstr(smsprov)
end sub

Function GatherRegInformation()
	Dim arrRegValueNames, arrRegValueTypes
	Dim dwValue
	Dim objRegLocator, objRegService
	Dim arrRegPrograms, strRegProgram, strRegProgramsDisplayName, strRegProgramsDisplayVersion, strRegProgramsTmp
	Dim bRegProgramsSkip
	Dim objRegExp
	
	Const HKEY_LOCAL_MACHINE = &H80000002
	If (bAllowErrors) Then
		On Error Resume Next
	End If
	ReportProgress VbCrLf & "Start subroutine: GatherRegInformation(" & strComputer & ")"
	
	If (bAlternateCredentials) Then
		Set objRegLocator = CreateObject("WbemScripting.SWbemLocator")
		Set objRegService = objRegLocator.ConnectServer(strComputer,"root\default",strUserName,strPassword)
		Set oReg = objRegService.Get("StdRegProv")
	Else
		Set oReg=GetObject("winmgmts:\\" &  strComputer & "\root\default:StdRegProv")
	End If
	
	If (Err <> 0) Then
	    Wscript.Echo Err.Number & " -- " &  Err.Description
	    Err.Clear
	    GatherRegInformation = False
	    Exit Function
	End If

	If (bRegDomainSuffix) Then
		ReportProgress " Reading domain information"
		oReg.GetStringValue HKEY_LOCAL_MACHINE,"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters","Domain", strPrimaryDomain
	End If

	If (bRegPrintSpoolLocation) Then
		ReportProgress " Reading print spool location"
		oReg.GetStringValue HKEY_LOCAL_MACHINE,"SYSTEM\CurrentControlSet\Control\Print\Printers","DefaultSpoolDirectory", strPrintSpoolLocation
	End If

	' Checking Terminal Server Settings
	oReg.GetDwordValue HKEY_LOCAL_MACHINE,"SYSTEM\CurrentControlSet\Control\Terminal Server","TSAppCompat", nTerminalServerMode
	
	If (bRegPrograms) Then
		ReportProgress " Reading Programs from Registry"
		Set objDbrRegPrograms = CreateObject("ADOR.Recordset")
		objDbrRegPrograms.Fields.Append "DisplayName", adVarChar, MaxCharacters
		objDbrRegPrograms.Fields.Append "DisplayVersion", adVarChar, MaxCharacters
		objDbrRegPrograms.Open
		Set objRegExp = New RegExp
		oReg.EnumKey HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall",arrRegPrograms
		For Each strRegProgram In arrRegPrograms
			bRegProgramsSkip = False
			oReg.GetStringValue HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" & strRegProgram, "DisplayName", strRegProgramsDisplayName
			
			' Remove programs without Display Name
			If (IsNull(strRegProgramsDisplayName)) Then : bRegProgramsSkip = True : End If 
	
			' Remove MSI applications
			If (Len(strRegProgram) = 38) Then 
				strRegProgramsTmp = Left(strRegProgram,1) & Right(strRegProgram,1)
				If (strRegProgramsTmp = "{}") Then : bRegProgramsSkip = True : End If
			End If
			
			' Remove Patches
			objRegExp.IgnoreCase = True
			objRegExp.Pattern = "KB\d{6}"
			strRegProgramsTmp = objRegExp.Test(strRegProgram)
			If (strRegProgramsTmp) Then : bRegProgramsSkip = True : End If
			objRegExp.Pattern = "Q\d{6}"
			strRegProgramsTmp = objRegExp.Test(strRegProgram)
			If (strRegProgramsTmp) Then : bRegProgramsSkip = True : End If

			
			If Not (bRegProgramsSkip) Then
				objDbrRegPrograms.AddNew
				objDbrRegPrograms("DisplayName") = strRegProgramsDisplayName
				
				oReg.GetStringValue HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\" & strRegProgram, "DisplayVersion", strRegProgramsDisplayVersion
				objDbrRegPrograms("DisplayVersion") = Scrub(strRegProgramsDisplayVersion)
				
				
				objDbrRegPrograms.Update
			End If
		Next
		objDbrRegPrograms.Sort = "DisplayName"
	End If
	
	If (bRegLastUser) Then
		ReportProgress " Reading last user"
		oReg.GetStringValue HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon","DefaultDomainName", strLastUserDomain
		oReg.GetStringValue HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon","DefaultUserName", strLastUser
		If (Len(strLastUserDomain) > 0) Then
			strLastUser = strLastUserDomain & "\" & strLastUser
		End If
	End If

	If (bRegWindowsComponents) Then
		ReportProgress " Reading Windows Components information"
		Set objDbrWindowsComponents = CreateObject("ADOR.Recordset")
		objDbrWindowsComponents.Fields.Append "Name", adVarChar, MaxCharacters
		objDbrWindowsComponents.Fields.Append "DisplayName", adVarChar, MaxCharacters
		objDbrWindowsComponents.Fields.Append "Class", adVarChar, MaxCharacters
		objDbrWindowsComponents.Fields.Append "ClassName", adVarChar, MaxCharacters
		objDbrWindowsComponents.Fields.Append "Level", adVarChar, MaxCharacters
		objDbrWindowsComponents.Open
		oReg.EnumValues HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\OC Manager\Subcomponents", arrRegValueNames, arrRegValueTypes
		For i=0 To Ubound(arrRegValueNames)
			oReg.GetDWORDValue HKEY_LOCAL_MACHINE,"SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\OC Manager\Subcomponents",arrRegValueNames(i), dwValue
			If (dwValue = 1) Then
				ReturnWindowsComponentName arrRegValueNames(i)
			End If
	
		Next
		objDbrWindowsComponents.Sort = "Class, DisplayName"
	End If
	
	ReportProgress "End subroutine: GatherRegInformation()"
	GatherRegInformation = True
End Function ' GatherRegInformation


Function WMIDateStringToDate(dtmDate)
dim temp
'WScript.Echo dtm: 
	temp = CDate(Mid(dtmDate, 5, 2) & "/" & _
	Mid(dtmDate, 7, 2) & "/" & Left(dtmDate, 4) _
	& " " & Mid (dtmDate, 9, 2) & ":" & Mid(dtmDate, 11, 2) & ":" & Mid(dtmDate,13, 2))
'ReportProgress temp
WMIDateStringToDate = temp
End Function



