WordPress.com



Const ScriptVersion = "4.18"'=============== Info =======================================' USEAGE: CLIENT HEALTH REPAIR' Based on source at: Rob Olson at Dude Works ' ' Based on source at: Brian Mason at ' Based on source at: ' Based on source at: Shaun Cassells at ''============================================================' Requirements' Requires sc.exe either present in run directory, %systemroot%\system32\, or %systemroot%\system32\dllcache' Requires regsrv32.exe to be in %systemroot%\system32\ or accessible in path'============================================================' Overview' The following script fixes generic workstation issues in a networked corporate environment' not designed to run on servers'''============================================================' 4.18 updates - Shaun Cassells''''Area's that need improvement' * Checking the SMS Client' * Install methods for SMS/ConfigMgr Client' * ConfigMgr 2007 specific changes' * WMI fixing / integration with WMIDiag.vbs (see )' * BITS Checking - Correct security' * BITS version correct''============================================================'On Error Resume NextDim objWMIService, oWMIService, oServicesDim ADSiteNameDim oUIResManagerDim oCache, CacheSizeDim SiteName,SiteCode,GUID,Version,strComputerRoleDim dd,strLogFile,tempPath,CCM_DIR,ddrDim CLIENTSTATE,StrERRTypeDim strValue,strValuesDim GoodLogPath,BadLogPath,logGood,LogBad,doRunCheck,eventlogDim StrCCRServer,strCCRSiteCode,strLOGServerDim LocalAdminGroup,admACCTDim do_CHK_LOCALADMIN,do_CHK_ADMSHARE,do_CHK_RemoteReg,do_CHK_WMI_SERVICE,do_CHK_BITS_SERVICE,do_CHK_REGXMLDim do_CHK_AdvClient,do_SEND_CCR,do_RUN_CCMSetUP,do_REBUILD,do_REPAIR,do_CHK_DCOM,do_StartSeriviceViaSC,SCEXELocationDim intEventType,strEventDescriptionDim iniResultDim sOStype,isOS,OS, sOSversionDim strEnvLog, strEnvValDim SMSCLIENTLASTERRORDim oSmsversion,SMSVersion,ConfigMgrVersion' ==================================================================='===========File System Constants====================================' ===================================================================Const ForReading = 1, TemporaryFolder = 2, ForAppending = 8Const OverwriteExisting = True' ==================================================================='===========Registry Constants=======================================' ===================================================================Const HKeyName_LOCAL_MACHINE = &H80000002'Const HKeyName_CURRENT_USER = &H80000001' ==================================================================='===========Event Log Constants======================================' ===================================================================Const EVENT_SUCCESS = 0Const EVENT_ERROR = 1Const EVENT_WARNING = 2Const EVENT_INFORMATION = 4Const AUDIT_SUCCESS = 8Const AUDIT_FAILURE = 16' ==================================================================='=============== Load/Create Objects ================================' ===================================================================On Error Resume NextDim WSHShell:Set WSHShell = CreateObject("WScript.Shell")If err <> 0 Then WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - WScript.Shell is broken" : CleanUp(err) 'Windows Scripting Host is busted!WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - Last Run @ " & nowDim objSysInfo:Set objSysInfo = CreateObject("ADSystemInfo")If err <> 0 Then WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - ADSystemInfo is broken" : CleanUp(err)Dim objFSO:Set objFSO = CreateObject("Scripting.FileSystemObject")If err <> 0 Then WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - Scripting.FileSystemObject is broken" : CleanUp(err)Dim oLocator:Set oLocator = CreateObject("WbemScripting.SWbemLocator")If err <> 0 Then WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - WbemScripting.SWbemLocator is broken" : CleanUp(err)'Dim objNetwork:Set objNetwork = WScript.CreateObject("work")On Error GoTo 0' ==================================================================='=============== GET ENVIRONMENT and LOGGING DETAILS ================' ==================================================================='Set Current Directorywshshell.CurrentDirectory = WScript.ScriptFullName & "\.."Dim strCurrentDir: strCurrentDir = wshSHELL.CurrentDirectoryDim Computer: Computer = WSHShell.ExpandEnvironmentStrings("%COMPUTERNAME%")Dim HomeDrive:HomeDrive = WSHShell.ExpandEnvironmentStrings("%HOMEDRIVE%")Dim windir:windir = WSHShell.ExpandEnvironmentStrings("%WINDIR%")Dim UserTempPath:UserTempPath = WSHShell.ExpandEnvironmentStrings("%TEMP%")'Check to see what state of client is in'Errors are incrementedCLIENTSTATE=0'Grab OS versionGetOs'Set Logfile locationStrERRType = ""strFileName = "sms_chk_" & computer & ".log"strLogFile = UserTempPath & "\" & strFileNamelenWinDir = Len(windir)strUNCLogFile = "\\" & Computer & "\admin$" & Right(UserTempPath,Len(UserTempPath)- lenWinDir) & "\" & strFileName' ===================================================================' ==========CONFIG SETTINGS==========================================' ==================================================================='/// Check System role, If role =0 or 1 Then WKS, 2 3 4 & 5 are Server roles'SMS 2003 SP2 versionSMSVersion="2.50.4160.2000"ConfigMgrVersion=""'AUTO because AD is extended with servers publishedWKS_ASSIGNSITECODE = "AUTO"WKS_CacheSize = 2048'Plenty large enough for service packsWKS_LocalAdminGroup = "Administrators"'SpecIfy Local Admin group to add SMS Admin Acount to (DEFAULT=Administrators)WKS_admACCT = "<EnterYoursHere>"'SpecIfy SMS Admin account (group)'//Registry for countsRegPath = "HKLM\SYSTEM\Setup\ClientHealthStartup"'Webpage to submit updates tostrWebAddress = ""'// CCR'sStrCCRServer = "<SITESERVER>"'SpecIfy Site server to send CCR's tostrCCRSiteCode = "<sc>"'If you use this method you need to grant 'DOMAIN\DOMAIN COMPUTERS write permissions (NFTS) to that share since the script runs under local systemGoodLogPath ="\\<EnterYoursHere>\SMSCLIENTLOGS\GPO\Good" 'SpecIfy Site server to send good/success logs(DEFAULT)BadLogPath ="\\<EnterYoursHere>\SMSCLIENTLOGS\GPO\Bad"'SpecIfy Site server to send bad/fail logs' Always capture your bad client logs so you can see who and where you have bad systems.'//CCMSetUP LOCATIONCCMSetUP = "\\<EnterYoursHere>\SMSClient\i386\ccmSetup.exe"'Path to CCMSetup.exe'Note this is the x32 path. x64 is differentCCM_DIR = windir & "\system32\CCM\"' ===================================================================' ==========Logging SETTINGS=========================================' ==================================================================='// LOGGINGlogToEventsSummary=True'Post single event log item that includes all events(DEFAULT=True)'LogToConsoleVerbose=False'wscript.echo the log file to the console (DEFAULT=False)LogToConsoleDebug=False'Wscript.echo for extra debugging (DEFAULT=False)LogEnvironment=True'Log environment, will aid in troubleshooting client, includes: system,user,process, volatileLogGood=False'copies the log file to a path designated below on a healthy machine (DEFAULT=False)LogBad=False'copies the log file to a path designated below on a healthy machine (DEFAULT=False)Do_WebSubmit = False 'Submits to a website for centralized reporting'Great for tracking trends via a webpage'Check Shaun's blog at (see header)LogRegCounter = False 'Writes totals to the Registry on the machine'Great for tracking trends via a SMS Def MOF'Check Shaun's blog at (see header)iHoursBetweenRun = 12 ' Number of hours that must have elapsed before next rundoRunCheck=False' Will only allow the script to fully run on a system once within iHoursBetweenRun hours' ===================================================================' ==========WMI SETTINGS=============================================' ==================================================================='// WMI REPAIR OPTIONS - WARNING - ONLY SELECT ONE OPTION TO REPAIR WMIdo_REBUILD = False'(DEFAULT=False)this option uses a BRUTE FORCE and renames the repository to repository_old and allows WMI to rebuild a new repository'this wil also wipe out any custom data you have stored in WMI- so beware - however this the MOST EFFECTIVEdo_REPAIR = True 'this option uses the repair upgrade option of WMI to attempt a gentle recovery without losing any custom data'If BOTH options are Set to False we will only log the WMI issue and you'll be able to manually deal with the WMI issues' however the script will NOT repair anything Else until WMI is fixed.' ===================================================================' ==========Functional Checks========================================' ==================================================================='// enable True / False tasks you wish to rundo_CHK_CheckLogFileModifyDate = True 'Check to see if log file is updating recentlydo_CHK_ASSIGNMENT = True' If a client is without an assignment, uses AD to determine assignmentdo_CHK_CCMEXEC = True' CHK_CCMEXEC should ALWAYS RUN - LEAVE at TRUEdo_CHK_AdvClient = True' Checks Advanced client state'Untested - do_SEND_CCRdo_SEND_CCR = False' Sends a CCR to your site server( only use If you dont use RUN_CCMSetUP )do_RUN_CCMSetUP = False' Runs CCMSetUP from specIfied server share location in order to reinstall the client'<COMMENT>' only use one install method CCR or CCMSetUP.. option is for enviroments where clients dont haven rights to write a CCR to the server but can pull CCMSetUP' Running CCMSetUP can be a little brutal but it should only happen once and its a much surer way to make sure that client gets installed correctly and right awaydo_CHK_SMSUPDATECLIENT = False' CHECK latest SMS client version and install updated client If needed.do_CHK_CACHESIZE = True' checks/Sets the cache size'Checksdo_CHK_SYSTEMPATH = True' Cleans up the System PATH statement environment by ensuring the wbem is near the front of and that there are no duplicates in the pathdo_CHK_DCOM = True' Forces DCOM security premissions for SMS client access'May not work currentlydo_CHK_LOCALADMIN = True' Adds your SMS Account to the local admins groupdo_CHK_ADMSHARE = True' checks and repairs Admin$'Servicesdo_CHK_RPC_SERVICE = True'Turns on RPC before everythingdo_CHK_WMI_SERVICE = True' Checks WMI servicedo_CHK_FIREWALL_ICS_SERVICE = True'Truns on ICS after WMIdo_CHK_SERVER_SERVICE = True' Checks Server Servicedo_CHK_RemoteReg = True' Enables remote registrydo_CHK_BITS_SERVICE = True' Checks BITS servicedo_CHK_WUS_SERVICE = True' Checks Automatic servicedo_CHK_TERMSERVICE_SERVICE = True' Checks Terminal servicedo_CHK_MSI_SERVICE = True' Checks Windows Installer service'Registerdo_CHK_REGXML = False' Registers XMLdo_CHK_REGBITS = False' Registers two Bits filesdo_CHK_REGOLEAut32 = False' Registers OLEAut32do_CHK_REGMsiexec = False' Registers msiexec /regserverDebug("********** Start ***********")'==================================================================='==================================================================='=================== START ========================================='==================================================================='==================================================================='check to see when last time script was run based on last log date' dont run more than once in 12 hrs' this prevents a client that is really hosed to not keep reinstalling everytime the user logs in' but rather attempts more fixes once a dayOn Error Resume NextIf doRunCheck=True ThenOn Error Resume NextIf objFSO.FileExists(strLogFile) Then Set ofile =objFSO.GetFile(strLogFile) 'Debug("Date diff = " & DateDIff("h", ofile.DateLastModified , Now)) 'Debug("iHoursBetweenRun = " & iHoursBetweenRun)If DateDIff("h", ofile.DateLastModified , Now) < iHoursBetweenRun ThenDebug("ran recently")WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - Ran less than " & iHoursBetweenRun & " hours ago " & NowCleanUp("doRunCheck")End IfEnd IfEnd If'Deletes the previous log fileIf objFSO.FileExists(strLogFile) ThenobjFSO.DeleteFile(strLogFile)End If'Creates new log fileSet oFile = objFSO.CreateTextFile(strLogFile)oFile.Closeerr.clearWSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - Last Full Run @ " & nowADSiteName = objSysInfo.SiteNameDebug("********** Begin System_Info ***********")COLLECTMSG "SYSTEM_INFO","SCRIPT_SOURCE","WKS"COLLECTMSG "SYSTEM_INFO","SCRIPT_VERSION",ScriptVersionCOLLECTMSG "SYSTEM_INFO","SCRIPT_LOCATION",strCurrentDirCOLLECTMSG "SYSTEM_INFO","SYSTEMNAME", ComputerCOLLECTMSG "SYSTEM_INFO","OPERATING_SYSTEM",OS & " " & sOSversionCOLLECTMSG "SYSTEM_INFO","SYSTEMROLE",strComputerRoleCOLLECTMSG "SYSTEM_INFO","LOGFILE", strLogFileCOLLECTMSG "SYSTEM_INFO","AD_USERNAME", objSysInfo.UserNameCOLLECTMSG "SYSTEM_INFO","AD_COMPUTERNAME", puterNameCOLLECTMSG "SYSTEM_INFO","AD_SITENAME", objSysInfo.SiteName' =============================================================================' RunTasks' Description: CONNECT TO MGMT SERVICE' =============================================================================Err.clearDebug("********** Chk DCOM & System Path & Local Admin Group ***********")If do_CHK_DCOM = True Then CHK_DCOMIf do_CHK_SYSTEMPATH = True Then CHK_SYSTEMPATH' This will ensure that the wbem path is near the front or the environment.SCFileExist' True if sc.exe file is found; False if not' Checks current path and %systemroot%\system32' SC.exe attempts to start a serviceIf isOS="workstation" Then If InStr(UCase(WScript.ScriptName),"SRV") Then CleanUp(err) LocalAdminGroup = WKS_LocalAdminGroupadmACCT = WKS_admACCT ASSIGNSITECODE = WKS_ASSIGNSITECODE CacheSize = WKS_CacheSizeElse'Disabled as this will not run on serversCOLLECTMSG "isOS","Error","Non workstation computer type"CleanUp(err)End IfIf do_CHK_LOCALADMIN = True Then CHK_SMSLOCALADMINDebug("********** Check WMI Service Mode ***********")COLLECTMSG "WMI Service",">",null'Check to see if Service is disabledSelect Case wshshell.regread("HKLM\SYSTEM\CurrentControlSet\Services\winmgmt\Start")Case 2'Auto setting - GOODCOLLECTMSG "WMI","Service in Reg is set to Auto",nullDebug("WMI is set to auto")Case 3'Manual setting - Connecting will start'Make service set to AutomaticCOLLECTMSG "WARNING","WMI","Service in Reg is set to Manual"Debug("WMI is set to Manual")RegCounter "WMI",1CLIENTSTATE = CLIENTSTATE + 1Case 4'Attempts to use sc.exe to start the serviceDebug("WMI Service is not set to AUTO")Debug("do_StartSeriviceViaSC = " & do_StartSeriviceViaSC)If do_StartSeriviceViaSC Then StartSeriviceViaSC "winmgmt","auto"RegCounter "WMI",1CLIENTSTATE = CLIENTSTATE + 1End Select' ============================================================================='CHECK If WMI IS ACCESSIBLE and CONNECT' =============================================================================Debug("********** Check WMI Connection ***********")On Error Resume NextSet objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2")If Err <> 0 ThenCOLLECTMSG "ERRORS","WMI_CONNECT",err & " " & err.descriptionDebug("********** WMI Connection FAIL ***********")RegCounter "WMI",1CLIENTSTATE = CLIENTSTATE + 1'//CANNOT CONNECT TO WMIDebug("Registry WMIStatus = " & WSHShell.Regread(RegPath & "\WMIStatus"))Select Case WSHShell.Regread(RegPath & "\WMIStatus")Case ""Debug("WMIStatus = no prior break") If do_REPAIR = True Then REPAIR_WMI_XP : RegCounter "WMIStatus","REPAIRED"Case "REPAIRED" Debug("WMIStatus = REPAIRED")If do_REBUILD = True Then REBUILD_WMI_BRUTE_FORCE : RegCounter "WMIStatus","REPAIRED"Case "REBUILT"Debug("WMIStatus = REBUILT")RegCounter "WMIFail",1CLIENTSTATE = CLIENTSTATE + 100COLLECTMSG "ERRORS","REBUILT","This machine has gone through Repair and Rebuild - still failing"End SelectIf LogBad=True ThenSet_LOGFOLDER()err.clearobjFSO.CopyFile strLogFile , BadLogPath, OverwriteExistingIf Err<>0 Then COLLECTMSG "LogBad","Error",err & " " & err.descriptionEnd Iferr.clearWSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - WMI " & WSHShell.Regread(RegPath & "\WMIStatus") & " " & NowDebug("ClientState = " & CLIENTSTATE)On Error GoTo 0CleanUp(err)End If'***Repleace with Registry counterRegCounter "WMIStatus",""'WriteEnvVar "SMSCLIENT_CHK_WMI_CONNECT","","system","0"'WriteEnvVar "SMSCLIENT_CHK_WMI_LAST","","system","0"' =============================================================================' RunTasks' Description: Generic Health Tasks' =============================================================================Err.clearDebug("********** Begin Checks ***********")If do_CHK_ADMSHARE = True Then CHK_ADMSHAREIf do_CHK_REGXML = True Then CHK_REGXMLIf do_CHK_REGBITS = True Then CHK_REGSVR32 "CHK_REGBITS", "Qmgr.dll" : CHK_REGSVR32 "CHK_REGBITS", "qmgrprxy.dll"If do_CHK_REGOLEAut32 = True Then CHK_REGSVR32 "CHK_REGOLEAut32", "OLEaut32.dll"If do_CHK_REGMsiexec = True Then CHK_REGMsiexecDebug("********** Begin Services ***********")If do_CHK_RPC_SERVICE = True Then Fix_Service "CHK_RPC_SERVICE","RpcSs","auto","Running"If do_CHK_WMI_SERVICE = True Then Fix_Service "CHK_WMI_SERVICE","winmgmt","auto","Running"If do_CHK_FIREWALL_ICS_SERVICE = True Then Fix_Service "CHK_FIREWALL_ICS_SERVICE","SharedAccess","auto","Running"If do_CHK_SERVER_SERVICE = True Then Fix_Service "CHK_SERVER_SERVICE","lanmanserver","auto","Running"If do_CHK_RemoteReg = True Then Fix_Service "CHK_RemoteReg","RemoteRegistry","auto","Running"If do_CHK_BITS_SERVICE = True Then Fix_Service "CHK_BITS_SERVICE","BITS","Manual","unimportant"If do_CHK_WUS_SERVICE = True Then Fix_Service "CHK_WUS_SERVICE","wuauserv","auto","Running"If do_CHK_TERMSERVICE_SERVICE = True Then Fix_Service "TERMSERVICE_SERVICE","TermService","Manual","unimportant"If do_CHK_MSI_SERVICE = True Then Fix_Service "MSI_SERVICE","MSIServer","Manual","unimportant"Debug("********** Begin SMS ***********")CHK_SMSVERSIONIf do_CHK_CCMEXEC = True Then Fix_Service "CHK_CCMEXEC","CcmExec","auto","Running"If do_CHK_SMSUPDATECLIENT = True Then CHK_SMSUPDATECLIENTCOLLECTMSG "SYSTEM_INFO","CLIENTSTATE",CLIENTSTATEDebug("Client State = " & CLIENTSTATE)If CLIENTSTATE = 0 Then' =============================================================================' RunTasks' Description: Run Healthy Client' =============================================================================Debug("********** Healthy last SMS ***********")If do_CHK_CheckLogFileModifyDate = True Then CheckLogFileModifyDate("PolicyEvaluator.log")If do_CHK_ASSIGNMENT = True Then CHK_ASSIGNMENT'now that everything is fixed we check that the client is assigned and If not we'll'force a new client install and since everything Else has now been fixed this new'install should take care of any last client hang ups, If your client still does not'function after this Then you need to reimage the computer because nothing Else is going to helpIf LogGOOD = True ThenCOLLECTMSG "SYSTEM_INFO","Set_LOGFOLDER",GoodLogPathSet_LOGFOLDER()err.clearobjFSO.CopyFile strLogFile , GoodLogPath , OverwriteExistingIf Err<>0 Then COLLECTMSG "LogGOOD","Error",err & " " & err.descriptionEnd IfWSHShell.LogEvent EVENT_INFORMATION, now & " SMS STARTUP SCRIPT/CLIENT STATE= HEALTHY"Else' =============================================================================' RunTasks' Description: Run Client Stupid Healing Tasks' =============================================================================Debug("********** NOT Healthy last SMS ***********")If do_CHK_AdvClient = True Then CHK_ADVCLIENTIf do_CHK_CACHESIZE = True Then CHK_CACHESIZEIf do_SEND_CCR = True Then SEND_CCRIf do_RUN_CCMSetUP = True Then RUN_CCMSetUPIf LogEnvironment = True ThenGetLogEnvironmentEnd IfIf LogBAD = True ThenCOLLECTMSG "SYSTEM_INFO","Set_LOGFOLDER",BadLogPathSet_LOGFOLDER()Err.clearobjFSO.CopyFile strLogFile , BadLogPath , OverwriteExistingIf Err<>0 Then COLLECTMSG "LogBAD","Error",err & " " & err.descriptionEnd If'Added now to Next line - not sure If that works with Event_WarningIf logToEventsSummary=True Then WSHShell.LogEvent EVENT_WARNING, Now & vbCRLF & eventlog & vbCrLf & strEnvLogEnd If'Clean upCleanUp(err)' =============================================================================' Method: CHK_SMSVERSION' Description: checks ccmexec file version, If no match latest version'reinstall latest client' =============================================================================Sub CHK_SMSVERSION()Dim objWMIServiceCLI,colCLIPropsList,colCLIPropsOn Error Resume NextCOLLECTMSG "CHK_SMSVERSION","SMSVERSION_SITE",SMSVersionSet objWMIServiceCLI = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & Computer & "\root\ccm")If Err <> 0 ThenCLIENTSTATE = CLIENTSTATE + 1StrERRType=StrERRType & "CHK_SMSVERSION_"COLLECTMSG "CHK_SMSVERSION","ERROR","Cannot connect to \ROOT\CCM client may not exist"Exit SubEnd IfSet colCLIPropsList = objWMIServiceCLI.ExecQuery("Select * from SMS_Client")For Each colCLIProps In colCLIPropsListCOLLECTMSG "CHK_SMSVERSION","VERSION", colCLIProps.ClientVersionoSmsversion=colCLIProps.ClientVersionDebug("Client Version " & oSmsversion)NextOn Error GoTo 0End Sub' =============================================================================' Method: CHK_SMSUPDATECLIENT' Description: checks SMS Client Version' =============================================================================Sub CHK_SMSUPDATECLIENT()If oSmsversion < SMSVersion ThenCLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_SMSUPDATECLIENT",1COLLECTMSG "CHK_SMSVERSION","UPDATE_SMSCLIENT","This system in not running the latest version SMS Client, reinstalling new client"RUN_CCMSetUPCOLLECTMSG "CHK_SMSVERSION","UPDATE_SMSCLIENT","Completed"End IfEnd Sub' =============================================================================' Method: CHK_SYSTEMPATH' Description: checks that wbem is near the front of the sys path and cleans'any duplicate statements from the path environment' =============================================================================Sub CHK_SYSTEMPATH()WindirPath = LCase(windir)System32path = LCase(windir & "\system32")WBEMpath = LCase(windir & "\system32\wbem")WindirPathFound = FalseSystem32pathFound = FalseWBEMpathFound = FalseSystemRoot = FalsestrKeyNamePath = "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"strValueName = "Path"'// GET PATH STATEMENTstrValue = wshshell.regRead("HKLM\" & strKeyNamePath & "\" & strValueName)strValue = LCase(strValue)ARRpath = Split(LCase(strValue), ";")For i = 0 To UBound(ARRpath)'Repalce SystemRoot with actual valueIf InStr(ARRpath(i), LCase("%systemroot%")) <> 0 Then strValue = Replace(strValue, LCase("%systemroot%"), LCase(windir)) : SystemRoot = True : COLLECTMSG "CHK_SYSTEMPATH","Warning Replaced %systemroot%",SystemRoot If ARRpath(i) = WindirPath Then WindirPathFound = True If ARRpath(i) = System32path Then System32pathFound = True If ARRpath(i) = WBEMpath Then WBEMpathFound = TrueNextIf (WBEMpathFound = True) And (System32pathFound = True) And (WindirPathFound = True) And (SystemRoot = False) Then COLLECTMSG "CHK_SYSTEMPATH","All Paths Found",WBEMpathFound: Exit SubCOLLECTMSG "CHK_SYSTEMPATH","PATH",strValue'// Log the resultslogit=FalseIf WBEMpathFound = False Then strValue = WBEMpath & ";" & strValue : COLLECTMSG "CHK_SYSTEMPATH","Error WBEMpathFound", WBEMpathFound:logit=True : CLIENTSTATE = CLIENTSTATE + 1If WindirPathFound = False Then strValue = WindirPath & ";" & strValue : COLLECTMSG "CHK_SYSTEMPATH","Error WindirPathFound", WindirPathFound :logit=True : CLIENTSTATE = CLIENTSTATE + 1If System32pathFound = False Then strValue = System32path & ";" & strValue : COLLECTMSG "CHK_SYSTEMPATH","Error System32pathFound",System32pathFound:logit=True : CLIENTSTATE = CLIENTSTATE + 1If logit = True Then StrERRType = StrERRType & "SYSTEMPATH_"'//Take out duplicates'Dictionary Object is Much faster ARRpath = Split(LCase(strValue), ";") Set PureString = CreateObject("Scripting.Dictionary") For i = 0 To UBound(ARRpath) If Not PureString.Exists(ARRpath(i)) Then PureString.Add ARRpath(i), ARRpath(i) : Debug(ARRpath(i)) NextstrValues = ""For Each strKeyName in PureString.KeysstrValues = strValues & strKeyName & ";"NextSet PureString = Nothing'Remove duplicate semicolonsIf InStr(strValues, ";;") <> 0 ThenstrValues = Replace(Replace(strValues, ";;", ";"), ";;", ";")'Remove trailing semicolons ln = Len(strValues) If InStr(ln, strValues, ";") <> 0 Then strValues = Left(strValues, ln - 1) '// Set PATH STATEMENT 'Set to current runtime path Set oEnv = WshShell.Environment("System") oEnv("Path")=strValues Set oEnv = Nothing 'Set to Registry for next restart wshshell.regwrite "HKLM\" & strKeyNamePath & "\" & strValueName,strValues,"REG_SZ" RegCounter "CHK_SYSTEMPATH",1 COLLECTMSG "CHK_SYSTEMPATH","PATH_CLEAN", strValuesEnd Sub' =============================================================================' Method: CHK_ADMSHARE' Description: Checks ADMIN SHARES ACCESS'Value Data: (0 = disable shares, 1 = enable)' =============================================================================Sub CHK_ADMSHARE()admShareFound = FalseSet colshares = objWMIService.ExecQuery("Select * from Win32_Share where Name = 'ADMIN$'")For Each objShare In colsharesadmShareFound = TrueCOLLECTMSG "CHK_ADMSHARE", "FOUND",admShareFoundNextIf admShareFound = False ThenCLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_ADMSHARE",1StrERRType=StrERRType & "CHK_ADMSHARE_"COLLECTMSG "CHK_ADMSHARE","FOUND",admShareFoundSet oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _Computer & "\root\default:StdRegProv")strKeyNamePath = "SYSTEM\CurrentControlSet\Services\LanManServer\Parameters"'strValueNameSRV = "AutoShareServer" ' for serversstrValueNameWS = "AutoShareWks" ' for workstationsoReg.SetDWORDValue HKeyName_LOCAL_MACHINE, strKeyNamePath, strValueNameWS, 1COLLECTMSG "CHK_ADMSHARE", "FIXED", NullEnd IfEnd Sub' =============================================================================' Method: CHK_AdvClient' Description: Checks CHK_AdvClient components' =============================================================================Sub CHK_ADVCLIENT()On Error Resume Next Dim oCPAppletMgr 'Control Applet manager object. Dim oClientComponent 'Individual client components. Dim oClientComponents 'A collection of client components. 'Get the Control Panel applet manager object. Set oCPAppletMgr = CreateObject("CPApplet.CPAppletMgr") If oCPAppletMgr Is Nothing Then CLIENTSTATE = CLIENTSTATE + 1 RegCounter "CHK_ADVCLIENT",1 Debug("Cannot connect to CPApplet.CPAppletMgr") StrERRType=StrERRType & "CHK_ADVCLIENT_"Exit Sub End If 'Get a collection of components. Set oClientComponents = oCPAppletMgr.GetClientComponents If oClientComponents Is Nothing Then Set oCPAppletMgr = Nothing Debug("No ADV Client Components") CLIENTSTATE = CLIENTSTATE + 1 RegCounter "CHK_ADVCLIENT",1 StrERRType=StrERRType & "CHK_ADVCLIENT_" Exit Sub End If For Each oClientComponent In oClientComponentsDebug(oClientComponent.DisplayName)Select Case oClientComponent.StateCase 0cmsg= "installed"Case 1cmsg= "enabled"Case 2cmsg= "disabled"End Select'If oClientComponent.DisplayName = "SMS Client Core Components" Then'CLIENTSTATE = oClientComponent.State'COLLECTMSG oClientComponent.DisplayName, oClientComponent.State, Null'End IfDisplayName=oClientComponent.DisplayNameCOLLECTMSG "CHK_ADVCLIENT",DisplayName,cmsgNext Set oClientComponents = Nothing Set oCPAppletMgr = Nothing If Err <> 0 Then COLLECTMSG "CHK_ADVCLIENT", "ERROR", NullOn Error GoTo 0End Sub' =============================================================================' Method: CHK_ASSIGNMENT' Description: Checks Client Site Assignment' =============================================================================Sub CHK_ASSIGNMENTOn Error Resume NextErr.clearDim oSMSClientSet oSMSClient = CreateObject ("Microsoft.SMS.Client")If err.Number<>0 ThenCOLLECTMSG "ERRORS","CHK_ASSIGNMENT", Err.descriptionCOLLECTMSG "CHK_ASSIGNMENT","Could not create SMS Client Object - Quitting", NullElseIf Len(oSMSClient.GetAssignedSite) = 0 ThenCLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_ASSIGNMENT",1'oSMSClient.SetAssignedSite("ABC")'have the client determine from AD or SLP appropraite site codeoSMSClient.ReAssignSiteCOLLECTMSG "CHK_ASSIGNMENT", "Client not installed correctly - Setting AUTO", Null StrERRType=StrERRType & "CHK_ASSIGNMENT_"End IfEnd IfSet oSMSClient=NothingOn Error GoTo 0End Sub' =============================================================================' Method: CHK_CACHESIZE' Description: Checks Client Cache Size' =============================================================================Sub CHK_CACHESIZEOn Error Resume NextSet oUIResManager = createobject("UIResource.UIResourceMgr")If oUIResManager Is Nothing ThenCLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_CACHESIZE",1COLLECTMSG "ERROR","CHK_CACHESIZE", Err.description COLLECTMSG "ERROR","CHK_CACHESIZE","Could not create Resource Manager - Quitting" StrERRType=StrERRType & "CHK_CACHESIZE_" Exit SubEnd IfSet oCache=oUIResManager.GetCacheInfo()If oCache Is Nothing Then Set oUIResManager=Nothing CLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_CACHESIZE",1 COLLECTMSG "ERROR","CHK_CACHESIZE","Could not get cache info - Quitting" StrERRType=StrERRType & "CHK_CACHESIZE_" Exit SubEnd IfoCache.TotalSize=CacheSizeCOLLECTMSG "CHK_CACHESIZE","CACHE SIZE", CacheSizeIf Err <> 0 Then COLLECTMSG "CHK_CACHESIZE", "ERROR", NullOn Error GoTo 0End Sub' =============================================================================' Method: CHK_SMSLOCALADMIN' Description: Adds your SMS Admin Account to the local admininstrators group' =============================================================================Sub CHK_SMSLOCALADMIN()COLLECTMSG "CHK_SMSLOCALADMIN",">", Null On Error Resume Next '>>> Add SMS ADMIN to Local Administrator groupIf InStr(admACCT, "\") <> 0 Then admACCT = replace(admACCT, "\", "/") Set objGroup = GetObject("WinNT://" & Computer & "/" & LocalAdminGroup & ",group") If Not objGroup.IsMember("WinNT://" & admACCT) ThenCLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_SMSLOCALADMIN",1'Change slash to allow addingobjGroup.Add ("WinNT://"& admACCT)COLLECTMSG "CHK_SMSLOCALADMIN", "Added", NullStrERRType=StrERRType & "LocalAdmin_" ElseCOLLECTMSG "CHK_SMSLOCALADMIN", "True" , Null End If If Err <> 0 Then COLLECTMSG "CHK_SMSLOCALADMIN","ERROR", Null On Error GoTo 0End Sub' =============================================================================' Method: REPAIR_WMI_XP' =============================================================================Sub REPAIR_WMI_XP()On Error Resume NextREPAIR_WMI_REGISTERIf do_StartSeriviceViaSC Then StartSeriviceViaSC "winmgmt","auto"COLLECTMSG "REPAIR_WMI_XP","CMD","rundll32 wbemupgd, UpgradeRepository"wshshell.run "rundll32 wbemupgd, UpgradeRepository",0,1StrERRType=StrERRType & "RepairWMI_"'WriteEnvVar "SMSCLIENT_CHK_WMI_LAST","REPAIRED","system","1"If Err <> 0 Then COLLECTMSG "ERROR", "REPAIR_WMI_XP", NullOn Error GoTo 0End Sub' =============================================================================' Method: REPAIR_WMI_2003' =============================================================================Sub REPAIR_WMI_2003()'This is never run 'Just for referenceOn Error Resume NextREPAIR_WMI_REGISTERIf do_StartSeriviceViaSC Then StartSeriviceViaSC "winmgmt","auto"wshshell.run "rundll32 wbemupgd, RepairWMISetup",0,1StrERRType=StrERRType & "RepairWMI_"COLLECTMSG "REPAIR_WMI_2003","cmd","rundll32 wbemupgd, RepairWMISetup"'WriteEnvVar "SMSCLIENT_CHK_WMI_LAST","REPAIRED","system","1"If Err <> 0 Then COLLECTMSG "ERROR", "REPAIR_WMI_2003", NullOn Error GoTo 0End Sub' =============================================================================' Method: REBUILD_WMI_BRUTE_FORCE' Description: Rebuilds WMI repository' =============================================================================Sub REBUILD_WMI_BRUTE_FORCE()On Error Resume NextREPAIR_WMI_REGISTERwshshell.run "net stop winmgmt /y",0,1WbemPath = windir & "\system32\wbem\Repository"'objFSO.MoveFolder WbemPath, WbemPath & "_Old"'Repalced the following line with StartSeriviceViaSC sub'wshshell.run "net start winmgmt",0,1REPAIR_WMI_MOFREPAIR_SMS_MOFIf do_StartSeriviceViaSC Then StartSeriviceViaSC "winmgmt","auto"StrERRType=StrERRType & "RebuildWMI_"COLLECTMSG "REPAIR_WMI","Finished", Null'WriteEnvVar "SMSCLIENT_CHK_WMI_LAST","REBUILT","system","1"If Err <> 0 Then COLLECTMSG "REBUILD_WMI_BRUTE_FORCE", "ERROR", NullOn Error GoTo 0End Sub' =============================================================================' Method: REPAIR_WMI_REGISTER' Description: Re-register WMI components' =============================================================================Sub REPAIR_WMI_REGISTER()On Error Resume NextCOLLECTMSG "REGISTER_WMI",">", Null'ClearADAPwshshell.run windir &"\system32\wbem\winmgmt.exe /CLEARADAP"'ReSynchPrefwshshell.run windir &"\system32\wbem\winmgmt.exe /RESYNCPERF"Set objFolder = objFSO.GetFolder(windir &"\system32\wbem")Set colFiles = objFolder.FilesFor Each objFile in colFiles If InStr(objFile.Name,".dll") Then wshshell.run "RegSvr32 /s " & objFile.Path,0,1 End If If InStr(objFile.Name,".exe") Then If InStr(objFile.Name,"wbemtest.exe") Then Else wshshell.run objFile.Path & " /RegServer",0,1 End If End If COLLECTMSG "REGISTER_WMI",objFile.Path, NullNextCOLLECTMSG "REGISTER_WMI","Finished", NullIf Err <> 0 Then COLLECTMSG "REGISTER_WMI", "ERROR", NullOn Error GoTo 0End Sub' =============================================================================' Method: REPAIR_WMI_MOF' Description: MofComp WMI MOF's' =============================================================================Sub REPAIR_WMI_MOF()On Error Resume NextCOLLECTMSG "REPAIR_WMI_MOF",">", NullSet objFolder = objFSO.GetFolder(windir &"\system32\wbem")Set colFiles = objFolder.FilesFor Each objFile in colFiles If InStr(objFile.Name,".mof") Then wshshell.run "mofcomp " & objFile.Path,0,1 End If If InStr(objFile.Name,".mfl") Then wshshell.run "mofcomp " & objFile.Path,0,1 End If COLLECTMSG "REPAIR_WMI_MOF",objFile.Path, NullNextCOLLECTMSG "REPAIR_WMI_MOF","Finished", NullIf Err <> 0 Then COLLECTMSG "REPAIR_WMI_MOF", "ERROR", NullOn Error GoTo 0End Sub' =============================================================================' Method: REPAIR_SMS_MOF' Description: MofComp SMS MOF's' =============================================================================Sub REPAIR_SMS_MOF()On Error Resume NextCOLLECTMSG "REPAIR_SMS_MOF",">", NullSet objFolder = objFSO.GetFolder(windir &"\system32\ccm")Set colFiles = objFolder.FilesFor Each objFile in colFiles If InStr(objFile.Name,".mof") Then wshshell.run "mofcomp " & objFile.Path,0,1 End If If InStr(objFile.Name,".mfl") Then wshshell.run "mofcomp " & objFile.Path,0,1 End If COLLECTMSG "REPAIR_SMS_MOF",objFile.Path, NullNextCOLLECTMSG "REPAIR_SMS_MOF","Finished", NullIf Err <> 0 Then COLLECTMSG "REPAIR_SMS_MOF", "ERROR", NullOn Error GoTo 0End Sub' =============================================================================' Method: CHK_REGXML' Description: Re-Registers XML DLL' =============================================================================Sub CHK_REGXML()On Error Resume NextCOLLECTMSG "CHK_REGXML",">", Null'// Register XMLXMLREG = windir & "\system32\regsvr32.exe /s " & windir & "\system32\msxml3.dll"COLLECTMSG "CHK_REGXML","CMD | " & XMLREG, NullSet oWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2:Win32_Process")result = oWMIService.Create(XMLREG, Null, Null, intProcessID)COLLECTMSG "CHK_REGXML","ProcessID | " & intProcessID, NullCOLLECTMSG "CHK_REGXML","Result | " & result, NullIf Err <> 0 Then COLLECTMSG "CHK_REGXML", "ERROR", Null : CLIENTSTATE = CLIENTSTATE + 1 : RegCounter "CHK_REGXML",1On Error GoTo 0End Sub' =============================================================================' Method: CHK_REGMsiexec' Description: Re-Registers msiexec' =============================================================================Sub CHK_REGMsiexec()On Error Resume NextCOLLECTMSG "CHK_REGMsiexec",">", Null'// Register XMLXMLREG = windir & "\system32\msiexec.exe /regserver"COLLECTMSG "CHK_REGMsiexec","CMD | " & XMLREG, NullSet oWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2:Win32_Process")result = oWMIService.Create(XMLREG, Null, Null, intProcessID)COLLECTMSG "CHK_REGMsiexec","ProcessID | " & intProcessID, NullCOLLECTMSG "CHK_REGMsiexec","Result | " & result, NullIf Err <> 0 Then COLLECTMSG "CHK_REGMsiexec", "ERROR", Null : CLIENTSTATE = CLIENTSTATE + 1 : RegCounter "CHK_REGMsiexec",1On Error GoTo 0End Sub' =============================================================================' Method: CHK_REGSVR32' Description: Re-Registers DLLs' =============================================================================Sub CHK_REGSVR32(nCHK, nFile)On Error Resume NextCOLLECTMSG nCHK,">", Null'// Register XMLREGsvr = windir & "\system32\regsvr32.exe /s " & windir & "\system32\" & nFileCOLLECTMSG nCHK,"CMD | " & REGsvr, NullSet oWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2:Win32_Process")result = oWMIService.Create(REGsvr, Null, Null, intProcessID)COLLECTMSG nCHK,"ProcessID | " & intProcessID, NullCOLLECTMSG nCHK,"Result | " & result, NullIf Err <> 0 Then COLLECTMSG nCHK, "ERROR", Null : CLIENTSTATE = CLIENTSTATE + 1 : RegCounter nCHK,1On Error GoTo 0End Sub' =============================================================================' Method: CHK_DCOM' Description: Sets DCOM sercurity premissions' =============================================================================Sub CHK_DCOM()COLLECTMSG "CHK_DCOM",">", Null'// Sets DCOMIf wshshell.regRead("HKLM\SOFTWARE\Microsoft\Ole\EnableDCOM") <> "Y" ThenCOLLECTMSG "CHK_DCOM", "ERROR", "EnableDCOM | write reg "wshshell.RegWrite "HKLM\SOFTWARE\Microsoft\Ole\EnableDCOM","Y","REG_SZ"CLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_DCOM",1End IfIf wshshell.regRead("HKLM\SOFTWARE\Microsoft\Ole\EnableRemoteConnect") <> "Y" ThenCOLLECTMSG "CHK_DCOM", "ERROR", "EnableDCOM | write reg "wshshell.RegWrite "HKLM\SOFTWARE\Microsoft\Ole\EnableRemoteConnect","Y","REG_SZ"CLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_DCOM",1End IfIf wshshell.regRead("HKLM\SOFTWARE\Microsoft\Ole\LegacyAuthenticationLevel") <> "2" ThenCOLLECTMSG "CHK_DCOM", "ERROR", "EnableDCOM | write reg "wshshell.RegWrite "HKLM\SOFTWARE\Microsoft\Ole\LegacyAuthenticationLevel","0x00000002","REG_DWORD"CLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_DCOM",1End IfIf wshshell.regRead("HKLM\SOFTWARE\Microsoft\Ole\LegacyImpersonationLevel") <> "2" ThenCOLLECTMSG "CHK_DCOM", "ERROR", "EnableDCOM | write reg "wshshell.RegWrite "HKLM\SOFTWARE\Microsoft\Ole\LegacyImpersonationLevel","0x00000002","REG_DWORD"CLIENTSTATE = CLIENTSTATE + 1RegCounter "CHK_DCOM",1End IfEnd Sub' =============================================================================' Method: SEND_CCR' Description: Sends a CCR' =============================================================================Sub SEND_CCR()COLLECTMSG "SEND_CCR",">", NullCCRPathFile = "\\"& StrCCRServer& "\SMS_" & strCCRSiteCode & "\inboxes\CCR.BOX\" & Computer & ".CCR" Set fsCCR = objFSO.CreateTextFile(CCRPathFile, True) fsCCR.writeline ("[NT Client Configuration Request]") fsCCR.writeline ("Machine Name=" & Computer) fsCCR.Close COLLECTMSG "SEND_CCR","SENT|" & CCRPathFile, NullEnd Sub' =============================================================================' Method: RUN_CCMSetUP' Description: Runs CCMSetUP to install SMS Client' =============================================================================Sub RUN_CCMSetUP()On Error Resume NextCOLLECTMSG "RUN_CCMSetUP",">", Null Set oWMIService = GetObject("winmgmts:" _ & "{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2:Win32_Process") result = oWMIService.Create(CCMSetUP & " SMSSITECODE=" & ASSIGNSITECODE & " SMSCACHESIZE=" & CacheSize & " DISABLECACHEOPT=TRUE DISABLESITEOPT=TRUE CCMHTTPPORT=712", Null, Null, intProcessID) COLLECTMSG "RUN_CCMSetUP","Path | " & CCMSetUP, NullCOLLECTMSG "RUN_CCMSetUP","SMSSITECODE | " & ASSIGNSITECODE, NullCOLLECTMSG "RUN_CCMSetUP","SMSCACHESIZE | " & CacheSize, NullCOLLECTMSG "RUN_CCMSetUP","ProcessID | " & intProcessID, NullCOLLECTMSG "RUN_CCMSetUP","Result | " & result, Null Set oWMIService = Nothing If Err <> 0 Then COLLECTMSG "RUN_CCMSetUP", "ERROR", Null : CLIENTSTATE = CLIENTSTATE + 1 : RegCounter "RUN_CCMSetUP",1On Error GoTo 0End Sub' =============================================================================' HELPERS' =============================================================================' =============================================================================' Method: GetSystemRole' Description: Checks System role' =============================================================================Function GetSystemRole()Set objWMIService = GetObject("winmgmts:" _& "{impersonationLevel=impersonate}!\\" & Computer & "\root\cimv2")Set colComputers = objWMIService.ExecQuery _("Select DomainRole from Win32_ComputerSystem")For Each objComputer In colComputersSelect Case objComputer.DomainRoleCase 0strComputerRole = "Standalone Workstation"Case 1strComputerRole = "Member Workstation"Case 2strComputerRole = "Standalone Server"Case 3strComputerRole = "Member Server"Case 4strComputerRole = "Backup Domain Controller"Case 5strComputerRole = "Primary Domain Controller"End SelectGetSystemRole=objComputer.DomainRoleNextEnd Function' =============================================================================' Determines OS by reading reg val & comparing to known values' OS version number returned as number of type double:' Windows Vista: 6' Windows 2k: 5' Windows XP: 5.1' Windows Server 2003: 5.2' Windows x: >5.2'' =============================================================================Sub GetOs()On Error Resume NextErr.clearsOStype = WSHShell.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\ProductOptions\ProductType")sOSversion = WSHShell.RegRead("HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\CurrentVersion")sOSType = Trim(sOSversion)If Err <> 0 ThenCLIENTSTATE = CLIENTSTATE + 1GetOsVersionNumber = "Unknown NTx"' Could not determine NT versionExit Sub ' >>>End IfSelect Case sOSversionCase 6Os = "Vista"isOS="workstation"Exit SubCase 5Os= "2000"isOS="workstation"Case 5.1Os = "XP"isOS="workstation"Exit SubCase 5.2Os = "2003"isOS="server"WSHShell.LogEvent EVENT_INFORMATION, "SMS STARTUP SCRIPT - Do not run on servers@ " & nowCleanUp(err)Exit SubEnd SelectIf IsOS ="workstation" And sOStype="WinNT" Then IsOS ="workstation" Else IsOS ="server"If Os= "2000" And sOStype="WinNT" Then IsOS ="workstation" Else IsOS ="server"On Error GoTo 0End Sub' =============================================================================' Method: StrDateTime' Description: Converts WMI TIME tokens' =============================================================================Function StrDateTime(d) Dim strDate Dim strTime Dim strVal strVal = CStr(d) strDate = DateSerial(Left(strVal, 4), _ Mid(strVal, 5, 2), _ Mid(strVal, 7, 2)) strTime = TimeSerial(Mid(strVal, 9, 2), _ Mid(strVal, 11, 2), _ Mid(strVal, 13, 2)) StrDateTime = strDate + strTimeEnd Function' =============================================================================' Method: Set_LogFolder' Description: Sets the logginf folder path' =============================================================================Sub Set_LOGFOLDER()If LogGood=True ThenGoodLogPath = GoodLogPathIf objFSO.FolderExists(GoodLogPath) Then Set objFolder = objFSO.GetFolder(GoodLogPath)Else Set objFolder = objFSO.CreateFolder(GoodLogPath)End IfEnd IfIf LogBad=True ThenBadLogPath = BadLogPathIf objFSO.FolderExists(BadLogPath) Then Set objFolder = objFSO.GetFolder(BadLogPath)Else Set objFolder = objFSO.CreateFolder(BadLogPath)End IfEnd IfGoodLogPath = GoodLogPath & "\" & StrERRType & computer & ".log"BadLogPath = BadLogPath & "\" & StrERRType & computer & ".log"End Sub' =============================================================================' Method: COLLECTMSG' Description: Collections Errors for logging to log file' =============================================================================Sub COLLECTMSG(Section,KeyName,value)On Error Resume NextDim fstrmsg=errmsgConst ForReading = 1, ForWriting = 2, ForAppending = 8Set f = objFSO.OpenTextFile(strLogFile, ForAppending, True)strmsg = now & " | " & Section & " | " & KeyName & " | "& valueIf Err <> 0 Thenstrmsg=strmsg & vbCrLf _& "Error | " & Hex(Err.Number) & " h (" & CStr(Err.Number) & ") | Description |" & Err.DescriptionEnd Ifeventlog=eventlog & strmsg & vbCrLff.Writeline strmsgVerboseCHK(strmsg)f.Closestrmsg=""Err.ClearOn Error GoTo 0End Sub' =============================================================================' Method: ReadEnvVar' Description: Read Environment Variables' =============================================================================Function ReadEnvVar(envField,envType)On Error Resume NextSelect Case envTypeCase "system"Set oEnv = WshShell.Environment("System")Case "user"Set oEnv = WshShell.Environment("User")Case "volatile"Set oEnv = WshShell.Environment("Volatile")Case "process"Set oEnv = WshShell.Environment("Process")End SelectReadEnvVar = oEnv(envField)On Error GoTo 0End Function' =============================================================================' Method: WriteEnvVar' Description: WMI Write Environment Variables' Depricated - writes to registry' =============================================================================Sub WriteEnvVar(envField,envValue,envType,envAddDel)On Error Resume NextSelect Case envTypeCase "system"Set oEnv = WshShell.Environment("System")Case "user"Set oEnv = WshShell.Environment("User")Case "volatile"Set oEnv = WshShell.Environment("Volatile")Case "process"Set oEnv = WshShell.Environment("Process")End Select' add a varIf envAddDel=1 Then oEnv(envField) = envValue' remove a varIf envAddDel=0 ThenoEnv.Remove envFieldOn Error GoTo 0End Sub' =============================================================================' Method: GetLogEnvironment' Description: Get Logs Environments' Depricated - writes to registry' =============================================================================Sub GetLogEnvironment()Dim fstrmsg=errmsgConst ForReading = 1, ForWriting = 2, ForAppending = 8Set f = objFSO.OpenTextFile(strLogFile, ForAppending, True)'// List all vars in all environment types'//System TypeSet oEnv = WshShell.Environment("System")For Each sItem In oEnvstrEnvVal = strEnvVal & sItem & vbCrLfNextstrEnvLog = strEnvLog & "[SystemEnvironment]" & vbCrLf & strEnvVal & vbCrLfstrEnvVal = ""'//Process TypeSet oEnv = WshShell.Environment("Process")For Each sItem In oEnvstrEnvVal = strEnvVal & sItem & vbCrLfNextstrEnvLog = strEnvLog & "[ProcessEnvironment]" & vbCrLf & strEnvVal & vbCrLfstrEnvVal = ""'//User TypeSet oEnv = WshShell.Environment("User")For Each sItem In oEnvstrEnvVal = strEnvVal & sItem & vbCrLfNextstrEnvLog = strEnvLog & "[UserEnvironment]" & vbCrLf & strEnvVal & vbCrLfstrEnvVal = ""'//Volatile TypeSet oEnv = WshShell.Environment("Volatile")For Each sItem In oEnvstrEnvVal = strEnvVal & sItem & vbCrLfNextstrEnvLog= strEnvLog & "[VolatileEnvironment]" & vbCrLf & strEnvVal & vbCrLfstrEnvVal = ""Set oEnv = Nothingf.Writeline strEnvLog f.CloseErr.ClearEnd Sub' =============================================================================' Method: StartWMIbyADSI' =============================================================================Sub StartWMIbyADSI()On Error Resume NextCOLLECTMSG "StartWMIbyADSI","ADSI","Start the service"' define a constant for stopped services' define ADSI status constantsConst ADS_SERVICE_STOPPED = 1Const ADS_SERVICE_START_PENDING = 2Const ADS_SERVICE_STOP_PENDING = 3Const ADS_SERVICE_RUNNING = 4Const ADS_SERVICE_CONTINUE_PENDING = 5Const ADS_SERVICE_PAUSE_PENDING = 6Const ADS_SERVICE_PAUSED = 7Const ADS_SERVICE_ERROR = 8' get an ADSI object for a computerSet objComputer = GetObject("WinNT://" & COMPUTER & ",computer")' get an object for a serviceSet objService = objComputer.GetObject("Service","winmgmt")' check to see if the service is stoppedIf (objService.Status = ADS_SERVICE_STOPPED) Then ' if the service is stopped, then start itobjService.Start If Err.number<>0 Then 'Exit sub 'Start Failed RegCounter "StartWMIbyADSI",1 wshshell.run SCEXELocation & " config winmgmt start= auto",0,1 wshshell.run SCEXELocation & " start winmgmt",0,1 CleanUp(err) End If While objService.Status <> ADS_SERVICE_RUNNING: WendEnd IfStrERRType=StrERRType & "StartWMIADSI_"'WriteEnvVar "StartWMIbyADSI","Started","system","1"If Err <> 0 Then COLLECTMSG "ERROR", "StartWMIbyADSI", NullOn Error GoTo 0End Sub' =============================================================================' Method: StartSeriviceViaSC' =============================================================================Sub StartSeriviceViaSC(ServiceName, nMode)On Error Resume NextDebug("ServiceName = " & ServiceName)Debug("nMode = " & nMode)COLLECTMSG "ERRORS","StartSeriviceViaSC",ServiceName & " Service not running"COLLECTMSG "INFO","StartSeriviceViaSC","Attempting to start via sc.exe"errreturn = 0Debug("Set " & ServiceName & " to " & nMode & " = " & SCEXELocation & " config " & ServiceName & " start= " & LCase(nMode))errreturn = wshshell.run(SCEXELocation & " config " & ServiceName & " start= " & LCase(nMode),0,1)Debug("errreturn = " & errreturn)If errreturn <> 0 ThenDebug("Errored out in " & ServiceName & " during StartSeriviceViaSC")RegCounter "StartSeriviceViaSC",1COLLECTMSG "ERRORS","StartSeriviceViaSC","sub was unable to set service " & ServiceName & " to zero"Exit SubEnd IfDebug(LCase(nMode) & " = auto")If LCase(nMode) = "auto" Then errreturn = 0errreturn = wshshell.run(SCEXELocation & " start " & ServiceName,0,1)Debug("errreturn = " & errreturn)If errreturn <> 0 ThenRegCounter "StartSeriviceViaSC",1Debug("ErrReturn = " & errreturn)COLLECTMSG "ERRORS","StartSeriviceViaSC","sub was unable to start service" & ServiceNameExit SubElseDebug("Successfully Started " & ServiceName)'Debug("Sleeping 500")'WSHShell.sleep(500)End IfEnd IfCOLLECTMSG "INFO","StartSeriviceViaSC","Service is set to " & nModeStrERRType=StrERRType & "StartWMISC_"'WriteEnvVar "StartSeriviceViaSC","Started","system","1"If Err <> 0 Then COLLECTMSG "ERROR", "StartSeriviceViaSC", NullOn Error GoTo 0End Sub' =============================================================================' Method: Fix_Service' Description: Checks the status of a service' =============================================================================Sub Fix_Service(nCHK, nService,nMode,nStatus)On Error Resume Next'Variable to identify when a service is missing' Example Bits is not installedDim bServiceFound: bServiceFound = FalseCOLLECTMSG nCHK,">", Nullerr.clearSet colServiceList = objWMIService.ExecQuery _("Select * from Win32_Service where Name = '" & nService &"'")If Err<>0 Then COLLECTMSG "Fix_Service","Error execQuery",err & " " & err.descriptionDebug("Err = " & err & " " & err.description)If do_StartSeriviceViaSC Then StartSeriviceViaSC nService, nModeEnd Iferr.clearFor Each objService In colServiceList'Found a service'Debug("objService Name = " & objService.name)'Debug("objService Caption = " & objService.Caption)bServiceFound = True'COLLECTMSG nCHK,"Mode | " & objService.StartMode, Null'COLLECTMSG nCHK,"Status | " & objService.State, Null'Added this check in for services that mode matters but not status'If the status is unimportant then ignore the tests belowIf nStatus = "unimportant" ThentempStatus = objService.StateElsetempStatus = nStatusEnd If'Debug("tempStatus = " & tempStatus)If LCase(objService.StartMode) <> LCase(nMode) Or LCase(objService.State) <> LCase(tempStatus) Then'Debug(objService.StartMode & " <> " & nMode)'Debug(objService.State & " <> " & tempStatus)CLIENTSTATE = CLIENTSTATE + 1RegCounter nCHK,1COLLECTMSG nCHK,"Current StartMode " & objService.StartMode, "Error"COLLECTMSG nCHK,"Current State " & objService.State, "Error"COLLECTMSG nCHK,"Changing StartMode to " & nMode, "Error"err.clearerrReturnCode = 0If nMode = "auto" Then nMode = "automatic"errReturnCode = objService.ChangeStartMode(nMode)If errReturnCode <> 0 Then 'More detail here' (VS.85).aspxDebug("err = " & err & " " & err.description & " return code = " & errReturnCode)COLLECTMSG nCHK,"ChangedStartMode",errReturnCodeCOLLECTMSG nCHK,"Failed to Change StartMode | " & nMode, "Error" CLIENTSTATE = CLIENTSTATE + 1If do_StartSeriviceViaSC Then StartSeriviceViaSC nService, nModeEnd Iferr.clearIf ((tempStatus = "Running") Or (nStatus = "Manual")) And objService.State <> nStatus Then CLIENTSTATE = CLIENTSTATE + 1RegCounter nCHK,1err.clearerrReturnCode = objService.startserviceIf errReturnCode <> 0 Then Debug("err= " & err & " RC= " & errReturnCode & " " & err.description) COLLECTMSG nCHK,"Failed to Startservice | " & nMode, "Error" CLIENTSTATE = CLIENTSTATE + 1If do_StartSeriviceViaSC Then StartSeriviceViaSC nService, nModeEnd IfCOLLECTMSG nCHK,"Startservice | "& errReturnCode, "Info"End IfStrERRType=StrERRType & nService & "_"End IfNextIf bServiceFound=False ThenCOLLECTMSG nCHK,nService &" Found | FALSE", Null : CLIENTSTATE = CLIENTSTATE + 1 : RegCounter nCHK,1StrERRType=StrERRType & nService & "_"End IfIf Err <> 0 Then COLLECTMSG nCHK, "ERROR", null : CLIENTSTATE = CLIENTSTATE + 1 : RegCounter nCHK,1On Error GoTo 0End Sub' =============================================================================' Method: RegCounter subprocedure' Descriptoin: Takes the value from a KeyName and adds in the number' =============================================================================Sub RegCounter(KeyName, Number)If LogRegCounter = True ThenOn Error Resume NextCOLLECTMSG "RegCounter",">", KeyNameCurrentKeyName = WSHShell.Regread(RegPath & "\" & KeyName)Debug("Orginal CurrentKeyName = " & CurrentKeyName)If LCase(KeyName) <> LCase("WMIStatus") Then Number = CurrentKeyName + NumberDebug("New Number = " & Number)'Write new valueWSHSHell.RegWrite RegPath & "\" & KeyName, Number, "REG_SZ"'Write Time StampWSHSHell.RegWrite RegPath & "\" & KeyName & "_TIME", Now(), "REG_SZ"End IfEnd Sub' =============================================================================' Method: EmailMessage subprocedure' Descriptoin: Sends an email to designated account' =============================================================================Function EmailMessage(Subject, Body)' Removed due to support issuesEnd Function' =============================================================================' Method: WebSubmit' Description: WebPage submit to SQL function Version 2... no outside requirements' =============================================================================Function WebSubmit(StatusWeb) Dim strWebAddress, strPost, strRequest COLLECTMSG "WebSubmit",">", Null Dim oHTTP, HTTPPost On Error Resume Next ' Gather Info 'Debug(strWebAddress) If Len(StrERRType) = 0 Then StrERRType = "None" strPost = "Cname=" & Computer & "&LogFile=" & strUNCLogFile & "&ErrType=" & StrERRType & "&Status=" & StatusWeb COLLECTMSG "WebSubmit","Post", strPost strRequest = strWebAddress & " " & strPost 'Debug(strRequest) 'Submit Info Set oHTTP = CreateObject("Microsoft.XMLHTTP") oHTTP.open "POST", strWebAddress, false oHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded" oHTTP.setRequestHeader "Content-Length", Len(strRequest) oHTTP.send strPost WebSubmit = oHTTP.responseText COLLECTMSG "WebSubmit","Sent", Null 'Debug(WebSubmit) Set oHTTP = NothingEnd Function' =============================================================================' Method: ShowFileAccessInfo' Description: Get Last File Access Info' =============================================================================Function ShowFileAccessInfo(filespec) On Error Resume Next COLLECTMSG "ShowFileAccessInfo",">", Null If objFSO.FileExists(filespec) Then Set f = objFSO.GetFile(filespec) filespec_date = f.DateLastModified FSpace = Instr(filespec_date," ") - 1 ShowFileAccessInfo = Left(filespec_date,FSpace) COLLECTMSG "ShowFileAccessInfo",filespec & " file date", ShowFileAccessInfo Else'File is missingCOLLECTMSG "ShowFileAccessInfo","Error - No Log file to check", filespec End If On Error GoTo 0End Function' =============================================================================' Method: SCFileExist' Description: Does a file exist?' =============================================================================Sub SCFileExist() On Error Resume Next COLLECTMSG "SCFileExist",">", Null If objFSO.FileExists(strCurrentDir & "\sc.exe") Then SCEXELocation = strCurrentDir & "\sc.exe" do_StartSeriviceViaSC = True COLLECTMSG "SCFileExist",SCEXELocation,do_StartSeriviceViaSC ElseIf objFSO.FileExists(windir & "\system32\sc.exe") Then CLIENTSTATE = CLIENTSTATE + 1RegCounter "SCFileExist",1 SCEXELocation = windir & "\system32\sc.exe" do_StartSeriviceViaSC = True COLLECTMSG "SCFileExist",SCEXELocation,do_StartSeriviceViaSCElseIf objFSO.FileExists(windir & "\system32\dllcache\sc.exe") Then CLIENTSTATE = CLIENTSTATE + 1RegCounter "SCFileExist",1SCEXELocation = windir & "\system32\dllcache\sc.exe" do_StartSeriviceViaSC = True COLLECTMSG "SCFileExist",SCEXELocation,do_StartSeriviceViaSC Else CLIENTSTATE = CLIENTSTATE + 1RegCounter "SCFileExist",1 'SC.exe does not exist, do not run service startdo_StartSeriviceViaSC = FalseCOLLECTMSG "SCFileExist","Error - No sc.exe", do_StartSeriviceViaSC End If On Error GoTo 0End Sub ' ============================================================================= ' Method: CheckLogFileModifyDate' Description: SMS Logs recently updated' =============================================================================Sub CheckLogFileModifyDate(LogToCheck)On Error Resume Next COLLECTMSG "CheckLogFileModifyDate",">", Null strSMSPolEval = windir & "\system32\CCM\Logs\" & LogToCheck 'Debug(strSMSPolEval) startdate = ShowFileAccessInfo(strSMSPolEval) 'Debug(startdate) If isDate(startdate) Then diffdate = DateDiff("d", startdate, date()) Debug(diffdate) End If If diffdate > 14 Then COLLECTMSG "CheckLogFileModifyDate","Error", LogToCheck & " inactive for " & diffdate & " Days" Debug("File activity > 14 days Should repair client") smsClient.RepairClient End If On Error GoTo 0End Sub' =============================================================================' Method: VerboseCHK' Description: Debugging, writes to console' =============================================================================Sub VerboseCHK(output)If LogToConsoleVerbose Then wscript.echo outputEnd Sub' =============================================================================' Method: Debug' Description: Debugging, writes to console' =============================================================================Sub Debug(output)If LogToConsoleDebug Then wscript.echo outputEnd SubSub CleanUp(ErrorCode)On Error Resume NextDebug("********** Centralize Info ***********")'Used to count number of times this script has runRegCounter "RunCount", 1'Submit StatusIf ErrorCode <> "doRunCheck" And Do_WebSubmit Then WebSubmit(CLIENTSTATE)Debug("********** CleanUp Objects ***********")Set oHTTP = NothingSet objEmail = NothingSet colServiceList = NothingSet colComputers = NothingSet fsCCR = NothingSet oWMIService = NothingSet objComputer = NothingSet objService = NothingSet objFolder = NothingSet ColFiles = NothingSet ofile = NothingSet objWMIService = NothingSet colCLIPropsList = NothingSet objWMIServiceCLI = NothingSet PureString = NothingSet oEnv = NothingSet colshares = NothingSet oReg = NothingSet oClientComponents = NothingSet oCPAppletMgr = NothingSet oSMSClient = NothingSet oCache = NothingSet oUIResManager = NothingSet objGroup = NothingSet objSysInfo = NothingSet objNetwork = NothingSet WSHShell = NothingSet objSysInfo = NothingSet objFSO = NothingSet oLocator = NothingDebug("********** End ***********")Debug("ErrorCode = " & ErrorCode)If ErrorCode = "doRunCheck" Then Wscript.Quitwscript.quit ErrorCodeEnd Sub==============Missed an email? Check out the list archive: ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download