?

Log in

No account? Create an account

Previous Entry | Next Entry

More WSUS stuff

WSUS Server Diagnostic Tool
ResetAnchors: Force a full sync in the next subscription run.
PurgeUnneededFiles: Delete all files not needed on the WSUS server.
ResetForegroundDownload: Reset foreground content download in WSUS server
GetBitsStatus: Get the status of BITS jobs. This tool requires BitsAdmin.exe to be in PATH
GetConfiguration: Get the WSUS server configuration Information
GetLogs: Get the WSUS Server Installation/Debug Logs.
SetForegroundDownload: Enable foreground content download in WSUS server. This can be used for proxies that don't support range requests.


Client Diagnostic Tool

Force download and install of WSUS updates v2.11


Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
Const ForAppending = 8
Const ForWriting = 2
Const ForReading = 1
Const cdoSendUsingMethod = "http://schemas.microsoft.com/cdo/configuration/sendusing", _
      cdoSendUsingPort = 2, _
      cdoSMTPServer = "http://schemas.microsoft.com/cdo/configuration/smtpserver"

On Error GoTo 0
strScriptVer = "2.11 - Rob Dunn (uphold2001@hotmail.com)"

'below variables for progress indicators
Dim objShell, objProcessEnv, objSystemEnv, objNet, objFso, objSwitches
Dim query, item, acounter, blnExtendedWMI, blnProcessEvents
Dim dlgBarWidth, dlgBarHeight, dlgBarTop, dlgBarLeft, dlgProgBarWidth, dlgProgBarHeight 
Dim dlgProgBarTop, dlgProgBarLeft
Dim dlgBar, dlgProgBar, wdBar, objPBar, objBar, blnSearchWildcard
Dim blnProgressMode, blnDebugMode, dbgTitle
Dim dbgToolBar, dbgStatusBar, dbgResizable
Dim IE, objDIV, objDBG, strMyDocPath, strSubFolder, strTempFile, f1, ts, File2Load, objFlash
Dim dbgWidth, dbgHeight, dbgLeft, dbgTop, dbgVisible
'above variables for progress indicators

Dim strAction, regWSUSServer, ws, l, wshshell, wshsysenv, strMessage, strFrom, wsuslog
Dim strRestart, silenttext, restarttext, blnCallRestart, blnInstall, blnPrompt

Set WshShell = WScript.CreateObject("WScript.Shell")
Set WshSysEnv = WshShell.Environment("PROCESS")
Set ws = wscript.CreateObject("Scripting.FileSystemObject")
strComputer = wshShell.ExpandEnvironmentStrings("%Computername%")
'-------------------------------------------------------------------------------------
' User variables
'Turn on debugging.  This will show some of the variables that are being passed 
' while the script executes.
Intdebug = 0          

'Whether or not the remote user will see the status window.
'
' Possible options are: 
'0 = verbose
'1 = silent
Silent = 0 
      
'The location of the logfile (this is the file that will be parsed
' and the contents will be sent via email.                      
logfile = WshSysEnv("TEMP") & "\" & "vbswsus-status.log"

'This won't attach and mail yet - WUA holds on to the file, so I can't email it...yet.
' Maybe for future versions...
WSUSLog = wshShell.ExpandEnvironmentStrings("%windir%") & "\" & "WindowsUpdate.log"

'Full EXE path to WindowsUpdateAgent20-x86.exe.  It will install it silently if the PC needs it
sExePath = Chr(34) & "\\server\share\WindowsUpdate\WindowsUpdateAgent20-x86.exe" & Chr(34)
                                          
'arbitrary email address - reply-to
strMailFrom = "wsus_script@yourdomain.com"

'who are you mailing to?  Input mode only.  Command-line parameters take precedence
strMailto = "you@yourdomain.com" 	      

'set SMTP email server address here
strSMTPServer = "x.x.x.x"  	        

'This option isn't used any longer..., the log file will be the body of the message
strMessage = "Open the attached text file to review WSUS logfile"

'The computer name will follow this text when the script completes.
strSubject = "[WSUS Update Script] - WSUS Update log file from " 

'Version number of the Windows Update agent you wish to compare installed version
' against.  If the version installed is not equal to this version, then it will
' install the exe referred to in var 'sExePath' above.
strWUAgentVersion = "5.8.0.2469"				

'default option for manual run of the script.  Possible options are:
' prompt - (user is prompted to install)
' install - updates will download and install
' detect - updates will download but not install                                       
strAction = "install" 

'Turns email function on/off.  If an email address is specified in the command-line
' arguments, then this will automatically turn on ('1').
' 0 = off, don't email
' 1 = on, email using default address defined in the var 'strMailto' above.
blnEmail = 1

'tells the script to prompt the user (if running in verbose mode) to input the email
' address of the recipient they wish to send the script log file to.  The default
' value in the field is defined by the strMailto variable above.  
' 
'This only appears if no command-line arguments are given.  
'0 = do not prompt the user to type in an email address
'1 = prompt user to type in email address to send the log to.
promptemail = 0

'Tells the computer what to do after script execution if the script detects that 
' there is a pending reboot.
'
'Command-prompt supercedes this option.
'0 = do nothing
'1 = reboot
'2 = shutdown
strRestart = 0

'-------------------------------------------------------------------------------------

                      
Set l = ws.OpenTextFile (logfile, ForWriting, True)
l.writeline "---------------------------------------------------------------------------"
l.writeline "WSUS force update VBScript" & vbcrlf & Now & vbcrlf & "Computer: " & strComputer
l.writeline "Script version: " & strScriptVer
l.writeline "---------------------------------------------------------------------------"

Call checkupdateagent

Set objArgs = WScript.Arguments
'writelog("Arguments: " & wscript.arguments)
if intdebug = 1 then wscript.echo "Objargs.count = " & objArgs.count
If objArgs.Count > 0 Then
For I = 0 to objArgs.Count - 1
  If objArgs.Count > 0 Then 
    if instr(objargs(i),"action:") Then
      strArrAction = split(objargs(0),":")
      strAction = strArrAction(1)
      if intdebug = 1 then wscript.echo strAction
    ElseIf instr(objargs(i),"mode:") Then 
      strArrMode = split(objargs(i),":")
      silent = strArrMode(1)
      If lcase(silent) = "silent" then 
        silent = 1
      Elseif lcase(silent) = "verbose" then 
        silent = 0
      Else
        strMsg = "Invalid mode switch: " & silent & ".  Now aborting."
        
        Call ErrorHandler(strMsg,"true")
      End If
      
      Silenttext = strArrMode(1)
    ElseIf instr(objargs(i),"email:") Then 
      strArrEmail = split(objargs(i),":")
      strMailto = strArrEmail(1)
    ElseIf InStr(LCase(objargs(i)),"restart:") Then
    	strArrAction = split(objargs(i),":")
    	strRestart = strArrAction(1)
    End If
  End If
Next
Else
      'strAction = "prompt"
      If blnEmail = 1 and silent = 0 and promptemail = 1 Then strMailto = InputBox("Input the email address you would like the " _
       & "Windows Update agent log sent to:","Email WU Agent logfile to recipient",strMailto)
      If strMailto = "" Then wscript.quit
End If

Select Case silent
  Case 0
    silenttext = "Verbose"
  Case 1
    silenttext = "Silent"
  Case Else
End Select

Select Case strRestart
  Case 0
    restarttext = "Do nothing"
  Case 1 
    restarttext = "Restart if reboot is pending"
  Case 2 
    restarttext = "Shut down if reboot is pending"
  Case Else
End Select

writelog("Script action is set to: " & strAction)
writelog("Verbose/Silent mode is set to: " & silenttext)
writelog("Restart action is set to: " & restarttext)

Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
 strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
strValueName = "WUServer"
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,regWSUSServer
writelog("Checking local WU settings...")

Call GetAUSchedule()

writelog("Update Server: " & regWSUSServer)

strValueName = "TargetGroup"
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,regTargetGroup
writelog("Target Group: " & regTargetGroup)

Set autoUpdateClient = CreateObject("Microsoft.Update.AutoUpdate")
Set updateInfo = autoUpdateClient.Settings

Select Case updateInfo.notificationlevel
	Case 0 
	  writelog("WUA mode: WU agent is not configured.")
	Case 1 
	  writelog("WUA mode: WU agent is disabled.")
	Case 2
	  writelog("WUA mode: Users are prompted to approve updates prior to installing")
	Case 3 
	  writelog("WUA mode Updates are downloaded automatically, and users are prompted to install.")
	Case 4 
	  writelog("WUA mode: Updates are downloaded and installed automatically at a pre-determined time.")
	Case Else
End Select



fstyle = "tahoma,arial,verdana"
bgcolor1 = "aliceblue"
fformat = "<font face='" & fstyle & "'>"

'set some IE status indicator variables...
blnDebugMode = True
blnProcessEvents = True
blnSearchWildcard = False
blnProgressMode = True

Set updateSession = CreateObject("Microsoft.Update.Session")
Set updateSearcher = updateSession.CreateupdateSearcher()

On error resume next
writelog("Instantiating Searcher")
Set searchResult = updateSearcher.Search("IsInstalled=0 and Type='Software'")

If cstr(err.number) <> 0 Then
  If cstr(err.number) = "-2147012744" Then
    strMsg = "Error connecting to the remote Update server " _
      & "to pull new update information.  " & vbcrlf & vbcrlf & "Verify that the proxy " _
      & "settings are correct, or that you have authenticated through your " _
      & "web-filtering software/hardware." & vbcrlf & vbcrlf & "Actual error was: " _
      & " - Error [" & cstr(err.number) & "] - '" & err.description & "'"
    blnFatal = true
    
  ElseIf CStr(err.number) = "-2145107924" Then
    strMsg = "Error contacting the WSUS server (" & regWSUSServer & ").  " _
      & "Using cached information from last detect cycle.  " & vbcrlf & vbcrlf & "Verify that the server is online.  " _
      & "Script will continue." & vbcrlf & vbcrlf & "Actual error was: " _
      & " - Error [" & cstr(err.number) & "] - '" & err.description & "'"
    blnFatal = false

  ElseIf cstr(err.number) <> 0 and cstr(err.number) = "-2147012867" or CStr(err.number) = "-2145124309" Then 
    strMsg = "Error starting updatesearcher - - actual error was [" & err.number & "]" & chr(34) _
      & err.description & chr(34) & ".  This computer may be configured for SUS 1.0.  Update this " _
      & "computer's GPO/registry settings and retry the update script at that time."
    blnFatal = true
  Else
    strMsg = "Error - [" & err.number & "]" & chr(34) & err.description & chr(34) & "."
    blnFatal = false 
    
  End If
  
  Call ErrorHandler(strMsg,blnFatal)
End If
'ssManagedServer

If silent = 0 then 
  writelog("Calling IE Status Window")
  Call IEStatus
End If

Call CheckPendingStatus("beginning")

strMsg = "Refreshing WUA client information..."
if silent = 0 then objdiv.innerhtml = strMsg

'cause WU agent to detect
autoUpdateClient.detectnow()

strMsg = "WUA mode: <font color='navy'>" & strACtion & "</font><br>WSUS Server: " & regWSUSServer _
 & "<br>Target Group: " & regTargetGroup & "<br><br>List of applicable items on the machine: <br>"
writelog("WUA mode: " & straction)
writelog("WSUS Server: " & regWSUSServer)
If silent = 0 then objdiv.innerhtml = strMsg
writelog("Searching for missing updates")

For I = 0 To searchResult.Updates.Count-1
    Set update = searchResult.Updates.Item(I)
    strSearchResultUpdates = strSearchResultUpdates & update.Title & "<br>"
    writelog("Missing: " & searchResult.Updates.Item(i))
Next
    if silent = 0 then objdiv.innerhtml = strMsg & strsearchResultUpdates
    
If searchResult.Updates.Count = 0 Then
  strMsg = fformat & "There are no further updates needed for your PC at this time."
	if silent = 0 then objdiv.innerhtml = strMsg
	writelog(replace(strMsg,fformat,""))

  Call EndOfScript
  wscript.quit
End If

If intdebug = 1 then WScript.Echo vbCRLF & "Creating collection of updates to download:"
writelog("Creating collection of updates to download") 

Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")

For I = 0 to searchResult.Updates.Count-1
    Set update = searchResult.Updates.Item(I)
    strUpdates = strUpdates & update.Title & "<br>"
    updatesToDownload.Add(update)
Next

if silent = 0 then objdiv.innerhtml = ""
strMsg = fformat & "This PC requires updates from the configured Update Server" _
 & " (" & regWSUSServer & ").  " _ 
 & "<br><br> Downloading needed updates.  Please stand by..."
if silent = 0 then objdiv.innerhtml = strMsg
writelog(replace(replace(strMsg,fformat,""),"<br>",""))

Set downloader = updateSession.CreateUpdateDownloader() 
downloader.Updates = updatesToDownload
writelog("Downloading updates")
downloader.Download()

strUpdates = ""
strMsg = ""
if silent = 0 then objdiv.innerhtml = ""
strMsg = fformat & "List of downloaded updates: <br><br>"
if silent = 0 then objdiv.innerhtml = strMsg

For I = 0 To searchResult.Updates.Count-1
    Set update = searchResult.Updates.Item(I)
    If update.IsDownloaded Then
       strDownloadedUpdates = strDownloadedUpdates & update.Title & "<br>"
    End If
       writelog("Downloaded: " & update.Title)
       if silent = 0 then objdiv.innerhtml = strMsg & strDownloadedUpdates
Next

Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")

strUpdates = ""
strMsg = ""
if silent = 0 then objdiv.innerhtml = ""
strMsg = fformat & "Creating collection of updates needed to install:<br><br>" 
if silent = 0 then objdiv.innerhtml = strMsg

For I = 0 To searchResult.Updates.Count-1
    set update = searchResult.Updates.Item(I)
    If update.IsDownloaded = true Then
       strUpdates = strUpdates & update.Title & "<br>"
       updatesToInstall.Add(update)
    End If
       writelog("Adding to collection: " & update.Title)
       if silent = 0 then objdiv.innerhtml = strMsg & strUpdates	
Next

If lcase(strAction) = "prompt" Then 
  strMsg = "The Windows Update Agent has detected that this computer is missing updates from the " _
   & " configured server (" & regWSUSServer & ")." & vbcrlf & vbcrlf & "Would you like to install updates now?"
  strResult = MsgBox(strMsg,36,"Install now?")
  strUpdates = ""
  writelog(strMsg & " [Response: " & strResult & "]")
  strMsg = ""
  If silent = 0 then objdiv.innerhtml = ""

ElseIf strAction = "detect" Then
  strMsg = fformat & "Windows Update Agent has finished detecting needed updates.<br><br>" 
  writelog(replace(strMsg,fformat,""))
  
  if silent = 0 then objdiv.innerhtml = strMsg
  
  Call EndOfScript
  wscript.quit
ElseIf strAction = "install" Then
  strResult = 6
End If 

strUpdates = ""
if silent = 0 then objdiv.innerhtml = ""

If strResult = 7 Then
  strMsg = strMsg & "<br>User cancelled installation.  This window can be closed."
  writelog(replace(strMsg,"<br>",""))
  
  if silent = 0 then objdiv.innerhtml = strMsg

	WScript.Quit
ElseIf strResult = 6 Then
  strMsg = ""
	strMsg = fformat & "Installing updates... <br><br>"
  writelog(replace(replace(strMsg,fformat,""),"<br>",""))
  if silent = 0 then objdiv.innerhtml = strMsg
	Set installer = updateSession.CreateUpdateInstaller()
	installer.Updates = updatesToInstall
	blnInstall = true
	
	Set installationResult = installer.Install()
	
	'Output results of install
	strMsg = fformat & "Installation Result: " & installationResult.ResultCode & "<br><br>" _
	 & "Reboot Required: " & installationResult.RebootRequired & "<br><br>" _
	 & "Listing of updates installed and individual installation results: <br>"
	For I = 0 to updatesToInstall.Count - 1
		If installationResult.GetUpdateResult(i).ResultCode = 2 Then 
			strResult = "Installed"
		ElseIf installationResult.GetUpdateResult(i).ResultCode = 1 Then 
			strResult = "In progress"
		ElseIf installationResult.GetUpdateResult(i).ResultCode = 3 Then 
			strResult = "Operation complete, but with errors"
		ElseIf installationResult.GetUpdateResult(i).ResultCode = 4 Then 
			strResult = "Operation failed"
		ElseIf installationResult.GetUpdateResult(i).ResultCode = 5 Then 
			strResult = "Operation aborted"			
		End If
		writelog(updatesToInstall.Item(i).Title & ": " & strResult)
    strUpdates = strUpdates & updatesToInstall.Item(i).Title & ": " & strResult & "<br>"
	Next
	if silent = 0 then objdiv.innerhtml = strMsg & strUpdates
End If		

Call EndOfScript
wscript.quit

'-----------------------------------------------------------
'Function Writelog
'-----------------------------------------------------------
Function WriteLog(strMsg)
  l.writeline time & " - " & strMsg
End Function

'-----------------------------------------------------------
'Function IE Status
'-----------------------------------------------------------
Function IEStatus

'added by Rob - IE status indicator code
If blnProgressMode Then
	If blnDebugMode Then
		dbgTitle = "Windows Update Script " & strScriptVer
	Else
		dbgTitle = "Windows Update Script " & strScriptVer
	End If	
	dbgToolBar = False
	dbgStatusBar = False
	If blnDebugMode Then
		dbgResizable = True
	Else
		dbgResizable = False
	End If
	dbgWidth = 500
	dbgHeight = 320
	dbgLeft = 0
	dbgTop = 0
	dbgVisible = True
	dlgBarWidth = 380
	dlgBarHeight = 23 
	dlgBarTop = 80
	dlgBarLeft = 50
	dlgProgBarWidth = 0
	dlgProgBarHeight = 18 
	dlgProgBarTop = 82
	dlgProgBarLeft = 50
	dlgBar = "left: " & dlgBarLeft & "; top: " & dlgBarTop & "; width: " & dlgBarWidth _
	 & "; height: " & dlgBarHeight & ";"
	dlgProgBar = "left: " & dlgProgBarLeft & "; top: " & dlgProgBarTop & "; width: " _
	 & dlgProgBarWidth & "; height: " & dlgProgBarHeight & ";"
	wdBar = 1 * dlgBarWidth
End If

If blnProgressMode Then
	Set IE = CreateObject("InternetExplorer.Application")
	'strScriptVer = "version would go here"

	strTempFile = WshSysEnv("TEMP") & "\progress.htm"
	ws.CreateTextFile (strTempFile)
        Set f1 = ws.GetFile(strTempFile)
        Set ts = f1.OpenAsTextStream(2, True)
        ts.WriteLine("<!-- saved from url=(0014)about:internet -->")
        ts.WriteLine("<html><head><title>" & dbgTitle & " " & strScriptVer & " </title>")
        ts.WriteLine("<style>.errortext {color:red}")
     	ts.WriteLine(".hightext {color:blue}</style>")
	ts.WriteLine("</head>")
	ts.WriteLine(strHDRCode & " <br><strong><font size='2' color='" & fcolor & "' face='" & fstyle & "'>" _
	 	& "&nbsp Running Windows Update Client...<br>" _
	 	& "&nbsp &nbsp<br>")
	ts.WriteLine("<center><table width='100%' bgcolor='" & bgcolor1 & "'><tr><td>")
	If blnDebugMode Then
		ts.WriteLine("<body bgcolor ='" & stsBGColor & "' scroll='yes' topmargin='0' leftmargin='0'"_
		& " style='font-family: " & fstyle & "; font-size: 0.6em color: #000000;"_
		& " font-weight: bold; text-align: left'><center><font face=" & fstyle & ">"_
		& " <font size='0.8em'> <hr color='blue'>")
	Else
		ts.WriteLine("<body bgcolor = '" & stsBGColor & "' scroll='no' topmargin='0' leftmargin='0' "_
		& " style='font-family: " & fstyle & "; font-size: 0.6em color: #000000;"_
		& " font-weight: bold; text-align: left'><center><font face=" & fstyle & ">"_
		& " <font size='0.8em'> <hr color='blue'>")
	End If
	ts.WriteLine("<div id='ProgObject' align='left'align='left' style='width: 450px;height: 140px;overflow:scroll'></div><hr color='blue'>")			
	If blnDebugMode Then
		ts.WriteLine("<div id='ProgDebug' align='left'></div>")
	End If

	ts.WriteLine("<script LANGUAGE='JavaScript1.2'>")
	ts.WriteLine("<!-- Begin")
	ts.WriteLine("function initArray() {")
	ts.WriteLine("this.length = initArray.arguments.length;")
	ts.WriteLine("for (var i = 0; i < this.length; i++) {")
	ts.WriteLine("this[i] = initArray.arguments[i];")
	ts.WriteLine("   }")
	ts.WriteLine("}")
	ts.WriteLine("var ctext = ' ';")
	ts.WriteLine("var speed = 1000;")
	ts.WriteLine("var x = 0;")
	ts.WriteLine("var color = new initArray(")
	ts.WriteLine("'red',")
	ts.WriteLine("'blue'")
	ts.WriteLine(");")
	ts.WriteLine("document.write('<div id=" & Chr(34) & "ProgFlash" & Chr(34) & ">"_
	 & "<center>'+ctext+'</center></div>');")
	ts.WriteLine("function chcolor(){")
	ts.WriteLine("document.all.ProgFlash.style.color = color[x];")
	ts.WriteLine("(x < color.length-1) ? x++ : x = 0;")
	ts.WriteLine("}")
	ts.WriteLine("setInterval('chcolor()',1000);")
	ts.WriteLine("// End -->")
	ts.WriteLine("</script>")
	ts.WriteLine("<div id='ProgBarId' align='left'></div>")
	ts.WriteLine("</font></center>")
	ts.WriteLine("</tr></td>")
	ts.WriteLine("</table></center>")
	ts.WriteLine("</body></html>")
	ts.Close
	fctSetupIE(strTempFile)
	Set objDIV = IE.Document.All("ProgObject")
	If blnDebugMode Then
		Set objDBG = IE.Document.All("ProgDebug")
	End If
	Set objFlash = IE.Document.All("ProgFlash")
	Set objPBar = IE.Document.All("ProgBarId")
	Set objBar = IE.Document
End If
If silent = 1 Then
'remarked by Rob Set logwindow = ie.document.all.text1
End If
End Function
'*******************************************************************
'*	Name:	fctSetupIE
'*	Function:	Setup an IE windows of 540 x 200 to display 
'* 	progress information.
'*******************************************************************
Sub fctSetupIE(File2Load)
	IE.Navigate File2Load
	IE.ToolBar = dbgToolBar
	IE.StatusBar = dbgStatusBar
	IE.Resizable = dbgResizable
	Do
	Loop While IE.Busy
	IE.Width = dbgWidth
	IE.Height = dbgHeight
	IE.Left = dbgLeft
	IE.Top = dbgTop
	IE.Visible = dbgVisible
	wshshell.AppActivate("Microsoft Internet Explorer")
End Sub

Sub GetAUSchedule()
Set objAutoUpdate = CreateObject("Microsoft.Update.AutoUpdate")
Set objSettings = objAutoUpdate.Settings

Select Case objSettings.ScheduledInstallationDay
    Case 0
        strDay = "every day"
    Case 1
        strDay = "sunday"
    Case 2
        strDay = "monday"
    Case 3
        strDay = "tuesday"
    Case 4
        strDay = "wednesday"
    Case 5
        strDay = "thursday"
    Case 6
        strDay = "friday"
    Case 7
        strDay = "saturday"
    Case Else
        strDay = "The scheduled installation day is could not be determined."
End Select

If objSettings.ScheduledInstallationTime = 0 Then
    strScheduledTime = "12:00 AM"
ElseIf objSettings.ScheduledInstallationTime = 12 Then
    strScheduledTime = "12:00 PM"
Else
    If objSettings.ScheduledInstallationTime > 12 Then
        intScheduledTime = objSettings.ScheduledInstallationTime - 12
        strScheduledTime = intScheduledTime & ":00 PM"
    Else
        strScheduledTime = objSettings.ScheduledInstallationTime & ":00 AM"
    End If
    'strTime = "Scheduled installation time: " & strScheduledTime
End If

writelog("Windows update agent is scheduled to run on " & strDay & " at " & strScheduledTime)
End Sub

Sub CheckUpdateAgent() 

writelog("Checking version of Windows Update agent against version " _
 & strWUAgentVersion & "...")

bUpdateNeeded = True ' init value 

On Error Resume Next 
Set updateSession = CreateObject("Microsoft.Update.AgentInfo") 
If Err.Number = 0 Then 
  updateinfo = updateSession.GetInfo("ProductVersionString") 
  If updateInfo = strWUAgentVersion then 
    writelog("File versions match (" & updateinfo & "). Windows Update Agent is up to date.")
    bUpdateNeeded = False 
  End If 
End If 

If bUpdateNeeded Then 
  ' stop the Automatic Updates service 
  writelog("File version (" & updateinfo & ") does not match. Windows Update Agent 2.0 required.") 
  writelog("Stopping service 'wuauserv'")
  WshShell.Run "%SystemRoot%\system32\net.exe stop wuauserv", 1, True 
  ' install tha AU client 
  On Error Resume Next 
  writelog("Attempting to install agent from '" & sExePath & "'")
  WshShell.Run sExePath & " /quiet /norestart", 1, True 

  If CStr(err.number) <> 0 Then 
    blnFatal = false
    strMsg = "Error executing Agent EXE - [" & err.number & "]: " & err.description & " (" & sExePath & ")" 
    call ErrorHandler(strMsg,blnFatal)
  End If 
End If 

End Sub

'------------------------------------------------------------------------
'Function SendMail - email the warning file
'------------------------------------------------------------------------
Function SendMail(strFrom,strTo,strSubject,strMessage)
Dim iMsg, iConf, Flds

writelog("Calling sendmail routine")
writelog("To: " & strMailto)
writelog("From: " & strMailFrom)
writelog("Subject: " & strSubject)
writelog("SMTP Server: " & strSMTPServer)

'If silent = 0 Then objdiv.innerhtml = "<font face=" & strFontStyle & " color=" & strFontColor2& ">" _
' & "sending mail to " & strMailTo & "...</font><br>"

'//  Create the CDO connections.
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields

'//  SMTP server configuration.
With Flds
 	   .Item(cdoSendUsingMethod) = cdoSendUsingPort
     	   '//  Set the SMTP server address here.
    	   .Item(cdoSMTPServer) = strSMTPServer
    	   .Update
End With

'l.close

Dim r
Set r = ws.OpenTextFile (logfile, ForReading, False, TristateUseDefault)
strMessage = r.readall

'//  Set the message properties.
With iMsg
    Set .Configuration = iConf
        .To       = strMailTo
        .From     = strMailFrom
        .Subject  = strSubject
        '.TextBody = strMessage
End With

'iMsg.AddAttachment wsuslog
iMsg.HTMLBody = replace(strMessage,vbnewline,"<br>")
'//  Send the message.

iMsg.Send ' send the message.
If CStr(err.number) <> 0 Then
	'writelog("Problem sending mail to " & strSMTPServer & ".")
	'writelog("Error: " & err.description)
	strMsg = "Problem sending mail to " & strSMTPServer & "." _
   & "Error [" & err.number & "]: " & err.description
  
  Call ErrorHandler(strMsg,"false")
Else
  strStatus = "Connected successfully to email server " & strSMTPServer
	If silent = 0 Then objdiv.innerhtml = strStatus
	If silent = 0 Then objdiv.innerhtml = strStatus & "<br><br><font face=" & strFontStyle & " color=" & strFontColor2& ">" _
 & "sent email to " & strMailTo & "...</font><br><BR>" _
	 & "Script complete.<br><br><a href='" & logfile & "'>View log file</a>"
End If

WshShell.run "wuauclt.exe /detectnow",1,true

End Function

'------------------------------------------------------------------'
'Function RestartAction
'Sub to perform a restart action against the computer
'------------------------------------------------------------------'
Function RestartAction
  If silent = 0 Then objdiv.innerhtml = strStatus & "<br> Now performing restart action (" & restarttext & ")."
  wscript.sleep 4000
  writelog("Processing RestartAction")
	'On Error GoTo 0
	Dim OpSysSet, OpSys
	'writelog("Computer: " & strComputer & vbcrlf & "Restart Action: " & strRestart)

  	'On Error Resume Next
  	
	'Call WMI query to collect parameters for reboot action
	Set OpSysSet = GetObject("winmgmts:{(Shutdown)}//" & strComputer & "/root/cimv2").ExecQuery("select * from Win32_OperatingSystem"_
	 & " where Primary=true") 
	 
	If CStr(err.number) <> 0 Then 
	  strMsg = "There was an error while attempting to connect to " & strComputer & "." & vbcrlf & vbcrlf _
		 & "The actual error was: " & err.description
		blnFatal = true
    	Call ErrorHandler(strMsg,blnFatal)
	End If

  	Const EWX_LOGOFF = 0 
  	Const EWX_SHUTDOWN = 1 
  	Const EWX_REBOOT = 2 
  	Const EWX_FORCE = 4 
  	Const EWX_POWEROFF = 8 
	
	'set PC to reboot
	If strRestart = 1 Then

		For each OpSys in OpSysSet 
			opSys.win32shutdown EWX_REBOOT + EWX_FORCE
		Next 

	'set PC to shutdown
	ElseIf strRestart = 2 Then
				
		For each OpSys in OpSysSet 
			opSys.win32shutdown EWX_POWEROFF + EWX_FORCE
		Next 
  
  'Do nothing...
  ElseIf strRestart = "0" Then
    				
	End If
wscript.quit
End Function

'------------------------------------------------------------------'

Sub ErrorHandler(strMsg,blnFatal)

		If silent = 0 then wscript.echo strMsg
		writelog(strMsg)
		If blnFatal = true then wscript.quit

End Sub

'------------------------------------------------------------------'
'Function EndOfScript
'Function to close out the script
'------------------------------------------------------------------'
Function EndOfScript
  If blnInstall = true then Call CheckPendingStatus("end")
	on error goto 0
  writelog("WSUS VB Script finished")
  l.writeline "---------------------------------------------------------------------------"
  If blnCallRestart = true then writelog("Restart action will be called.  " _
   & "Restart action is set to: " & restarttext & ".")
     
  If blnEmail = 1 Then 
      Call SendMail(strFrom,strTo,strSubject & " from " & strComputer,strMessage)
  Else
      'l.close
  End If

  strMsg = "The script has been configured to " & restarttext _
   		& ".  The update script has detected that this " _
   		& "computer has a reboot pending from a previous update session." & vbcrlf & vbcrlf _
   		& "Would you like to perform this action now?"
  
  If silent = 0 and blnPrompt = true Then 
  	strResult = MsgBox(strMsg,36,"Perform restart/shutdown action?")
  ElseIf blnPrompt = false Then
  	strResult = 6
  End If
  
   
  If blnCallRestart = true Then 
  	If strResult = 6 Then call RestartAction
  Else
  	If silent = 0 Then objdiv.innerhtml = strStatus & "<br>This computer has no pending reboots"
  End If
  
  'l.close
  wscript.quit
  
End Function


'------------------------------------------------------------------'
'Function CheckPendingStatus
'Function to restart the computer if there is a reboot pending...
'------------------------------------------------------------------'
Function CheckPendingStatus(beforeorafter)
  Set ComputerStatus = CreateObject("Microsoft.Update.SystemInfo")
  Select case beforeorafter
    Case "beginning"
      strCheck = "Pre-check"
    Case "end"
      strCheck = "Post-check"
    Case Else
  End Select
  
  If ComputerStatus.RebootRequired Then
     If beforeorafter = "beginning" Then 
        strMsg = "This computer has a pending reboot (" & strCheck & ").  Switching to 'detect' mode."
        If strAction = "prompt" Then blnPrompt = true
        strAction = "detect"
        blnCallRestart = true  
     Else
        strMsg = "This computer has a pending reboot (" & strCheck & ").  Setting PC to perform post-script " _
          & "execution..."
        blnCallRestart = true        
     End If
  Else
        strMsg = "This computer does not have any pending reboots (" & strCheck & ")."
  End If
  
     writelog(strMsg)
     If silent = 0 then objdiv.innerhtml = strMsg
     'wscript.sleep 4000
           
End Function
'------------------------------------------------------------------'
 


Microsoft's Script to Force the Update Detection from Automatic Update Client for updates on WSUS Server

@echo off
Echo This batch file will Force the Update Detection from the AU client:
Echo 1. Stops the Automatic Updates Service (wuauserv)
Echo 2. Deletes the LastWaitTimeout registry key (if it exists)
Echo 3. Deletes the DetectionStartTime registry key (if it exists)
Echo 4. Deletes the NextDetectionTime registry key (if it exists)
Echo 5. Restart the Automatic Updates Service (wuauserv)
Echo 6. Force the detection
Pause
@echo on
net stop wuauserv
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v LastWaitTimeout /f
REG DELETE "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v DetectionStartTime /f
Reg Delete "HKLM\Software\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update" /v NextDetectionTime /f
net start wuauserv
wuauclt /detectnow
@echo off
Echo This AU client will now check for the Updates on the Local WSUS Server.
Pause

Tags:

Comments

( 2 comments — Leave a comment )
(Anonymous)
Dec. 20th, 2005 10:07 pm (UTC)
THANKS!!!
This script has made my week. Thanks!

dsol
rialtus
Dec. 20th, 2005 11:17 pm (UTC)
Re: THANKS!!!
Glad it helped.
( 2 comments — Leave a comment )